CRTP refer to typedef in derived class from base class

好久不见. 提交于 2019-12-10 15:03:21

问题


I have following code:

template <typename T>
class A
{
    typedef typename T::Type MyType;
};

template <typename T>
class B : public A<B<T>>
{
    typedef T Type;
};

When I try to instantiate B, I get following error message using MSVS 2015:

'Type': is not a member of 'B<int>'

Is this code valid C++ or is MSVS right?


回答1:


The problem is at this point

template <typename T>
class A
{
    typedef typename T::Type MyType;
                     ^^^
};

T needs to be a complete type. But in your case, when A<T> is instantiated here:

template <typename T>
class B : public A<B<T>>
                 ^^^^^^^

B<T> is not yet a complete type! So this cannot work unfortunately.

The simple solution is just to pass in Type separately:

template <typename T, typename Type>
class A
{
    typedef Type MyType;
};    

template <typename T>
class B : public A<B<T>, T>
{

};


来源:https://stackoverflow.com/questions/36268400/crtp-refer-to-typedef-in-derived-class-from-base-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!