CRTP:为什么获取派生类的嵌套类型和嵌套方法之间存在差异? [英] CRTP: why a difference between getting a nested type and nested method of the derived class?

查看:46
本文介绍了CRTP:为什么获取派生类的嵌套类型和嵌套方法之间存在差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CRTP 模式中的基类可以访问派生类的成员函数,但不能访问派生类中的嵌套类型.

The base class in the CRTP pattern can access the member functions of the derived class, but it can't access a nested type in the derived class.

为什么会有这种差异?

为了说明,请考虑以下代码:

To illustrate, consider the following piece of code:

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_type causes a compilation error, while crtp_method compiles fine, although both attempt to access something defined in the Derived class. What is the C++ specification that explains that difference?

推荐答案

这里的区别在于方法的实例化仅在您实际使用它时发生,而 crtp_base 的实例化发生在 public crtp_base<X> 其中类型 X 仍然不完整.解决方法是使用类型特征:

The difference here is that instantiation of method happens only when you actually use it while instantiation of crtp_base happens at public crtp_base<X> where type X is still incomplete. The workaround would be to use type traits:

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:为什么获取派生类的嵌套类型和嵌套方法之间存在差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆