CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
CRTP: why a difference between getting a nested type and nested method of the derived class?
CRTP模式中的基类可以访问派生类的成员函数,但不能访问派生类中的嵌套类型。
为什么会有这种差异?
为了进行说明,请考虑以下代码:
template<typename Derived>
struct crtp_base
{
void crtp_method() { return static_cast<Derived&>(*this).method(); } // compiles
using crtp_type = typename Derived::type; // doesn't compile
};
struct X : public crtp_base<X>
{
void method() {}
using type = int;
};
int main()
{
}
crtp_type
导致编译错误,而crtp_method
编译良好,尽管两者都试图访问Derived
类中定义的内容。解释这种差异的C++规范是什么?
这里的区别在于,方法的实例化仅在实际使用时发生,而crtp_base
的实例化发生在类型X
仍然不完整的public crtp_base<X>
。解决方法是使用类型特征:
template<typename x_Target>
struct Trait;
template<typename Derived>
struct crtp_base
{
void crtp_method() { return static_cast<Derived&>(*this).method(); }
using crtp_type = typename Trait<Derived>::type;
};
struct X;
template<>
struct Trait<X>
{
using type = int;
};
struct X : public crtp_base<X>
{
void method() {}
using type = Trait<X>::type;
};
相关文章:
- 单独定义模板化嵌套类方法的正确语法
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何在该接收类之外声明嵌套类的方法
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 如何重写继承的嵌套类中存在的虚拟方法
- CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
- 在 C 中并行化嵌套循环的几种方法之间的差异,C++使用 OpenMP
- 嵌套类的替代方法
- 许多变量,没有嵌套循环的最佳方法
- 在嵌套名称空间范围中使用名称空间的正确方法
- C++:将 Args && ... _args传递到嵌套列表的正确方法?
- 如何使用new()在嵌套类中调用方法
- 执行三个嵌套for循环的最快方法是什么
- 模板化方法中使用的嵌套类的未解析外部符号
- 覆盖我正在扩展的嵌套类的方法
- 定义类(和嵌套类)成员函数的更好/更整洁/更可读的方法
- 简单C++是嵌套布尔方法
- 静态嵌套bool会帮助我禁用对某些类型的调用吗?或者有更干净的方法吗
- 有没有一种方法可以将宏名称作为参数传递给嵌套宏,而在最外层宏展开时不展开它们
- C++嵌套方法try-catch(实践)