CRTP:为什么获取派生 class 的嵌套类型和嵌套方法之间存在差异?
CRTP: why a difference between getting a nested type and nested method of the derived class?
CRTP模式中的基础class可以访问派生class的成员函数,但不能访问派生class中的嵌套类型。
为什么会有这种差异?
为了说明,请考虑以下代码:
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
class 中定义的内容。解释这种差异的 C++ 规范是什么?
这里的区别在于,方法的实例化仅在您实际使用它时发生,而 crtp_base
的实例化发生在 public crtp_base<X>
处,其中类型 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;
};
CRTP模式中的基础class可以访问派生class的成员函数,但不能访问派生class中的嵌套类型。
为什么会有这种差异?
为了说明,请考虑以下代码:
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
class 中定义的内容。解释这种差异的 C++ 规范是什么?
这里的区别在于,方法的实例化仅在您实际使用它时发生,而 crtp_base
的实例化发生在 public crtp_base<X>
处,其中类型 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;
};