奇怪的重复模板 - 变体
Curiously recurring template - variation
本文关键字:变体 更新时间:2023-10-16
关于CRP,如果我想实现它的轻微变化(使用模板模板参数(,我会收到编译错误:
template <template <typename T> class Derived>
class Base
{
public:
void CallDerived()
{
Derived* pT = static_cast<Derived*> (this);
pT->Action(); // instantiation invocation error here
}
};
template<typename T>
class Derived: public Base<Derived>
{
public:
void Action()
{
}
};
我不完全确定人们会选择这种形式(它不能为我编译(而不是使用它(这有效(
template <typename Derived>
class Base
{
public:
void CallDerived()
{
Derived* pT = static_cast<Derived*> (this);
pT->Action();
}
};
template<typename T>
class Derived: public Base<Derived<T>>
{
public:
void Action()
{
}
};
这也应该编译。我们只需要显式指定其他模板参数
template <typename T, template <typename T> class Derived>
class Base
{
public:
void CallDerived()
{
Derived<T>* pT = static_cast<Derived<T>*> (this);
pT->Action(); // instantiation invocation error here
}
};
template<typename T>
class Derived: public Base<T,Derived>
{
public:
void Action()
{
}
};
在第一个示例中,类模板实际上采用模板模板参数,而不仅仅是模板参数,正如您所写的那样:
template <template <typename T> class Derived>
class Base
{
//..
};
所以这段代码没有意义:
Derived* pT = static_cast<Derived*> (this);
pT->Action(); // instantiation invocation error here
这里Derived
是一个模板模板参数,它需要您没有提供给它的模板参数。实际上,在CallDerived()
函数中,您无法知道需要向其提供哪种类型才能执行打算执行的操作。
第二种方法是正确的解决方案。使用它。
相关文章:
- std::具有相同基类的类的变体
- 访问者访问变体并返回不同类型时出错
- 我应该使用什么来代替void作为变体中的替代类型之一
- 将shared_ptr移动到<StructA>shared_ptr<变体<结构A、结构 B>>
- 如何比较自定义类的std::变体
- 通过网络、跨平台传递std::变体是否安全
- 对于循环变体比较
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 标准::变体的赋值运算符
- 如何@ref同一方法的不同变体?
- 无限嵌套具有变体的地图
- Android Studio:如何在build.gradle中定义自定义宏(针对不同的构建变体),并让原生C / C++
- std::带有前向声明的变体
- 如何将 std::filesystem::p ath 转换为 LPCSTR,以便在 LoadLibrary() 变体之一
- 如何使用可变参数模板强制转换每个变体类型
- 标准::C++中的变体
- 你如何使std::变体的使用更"palatable",语法方面?
- 访问具有单状态的变体
- 确保无变体的型号安全
- 类型双关主题的变体:就地琐碎构造