c++ - CRTP 派生的模板化方法调用在“>”标记之前产生预期的主表达式
问题描述
以下示例无法编译并出现错误error: expected primary-expression before ‘>’ token
。我不懂为什么。我正在尝试调用派生的 CRTP 模板化方法。我用 CRTP 这样做是因为你不能有virtual
模板化的方法。
#include <iostream>
#include <memory>
#include <type_traits>
struct Foo
{
Foo(int xx, int yy) : x(xx), y(yy) {}
int x, y;
};
struct Bar
{
Bar(int xx, int yy, int zz) : x(xx), y(yy), z(zz) {}
int x, y, z;
};
template<class Derived = void>
class Base
{
public:
template<class T>
std::unique_ptr<T> makeTImpl(int x, int y) {
return std::make_unique<T>(x, y);
}
template<class T>
std::unique_ptr<T> makeT(int x, int y)
{
if constexpr (std::is_same_v<Derived, void>) {
return makeTImpl<T>(x, y);
} else {
auto& d = *static_cast<Derived*>(this);
return d.makeTImpl<T>(x, y); // error: expected primary-expression before ‘>’ token
}
}
};
class Derived : public Base<Derived>
{
public:
Derived(int z) : _z(z) {}
template<class T>
std::unique_ptr<T> makeTImpl(int x, int y) {
return std::make_unique<T>(x, y, _z);
}
private:
int _z;
};
int main() {
Base b;
b.makeT<Foo>(1, 2);
Derived d(3);
d.makeT<Bar>(1, 2);
}
解决方案
推荐阅读
- bash - 计算文件名字符,然后将这些文件复制到另一个目录
- c# - 使用下拉列表搜索不起作用
- ruby-on-rails - 带有父字段的 Ruby-on-Rails Where 子句
- hash - 用 160 位计算哈希冲突
- python-2.7 - 如何在odoo-11的create方法中调用向导?
- visual-studio-2015 - 构建/重建抛出 System.ExecutionEngineException 错误
- sql - SQL Server 正在尝试使用两个路径作为备份位置
- firebase - Firebase 存储更改图像方向
- javascript - 使用 insertOne nodejs 将两个数组中的键值对添加到 mongoDB
- wpf - 键盘无法访问 DataGrid 标头