“继承”类型使用CRTP和typedef [英] "Inherited" types using CRTP and typedef
问题描述
以下代码无法编译。
我得到一个错误消息:错误C2039:'Asub':不是'C'的成员
有人可以帮我理解这个吗? p>
试用VS2008& 2010编译器。
模板< class T&
class B
{
typedef int Asub;
public:
void DoSomething(typename T :: Asub it)
{
}
};
class C:public B< C>
{
public:
typedef int Asub;
};
class A
{
public:
typedef int Asub;
};
int _tmain(int argc,_TCHAR * argv [])
{
ChingThing;
theThing.DoSomething(C :: Asub());
return 0;
}
到编译器这里 - C
是不完整的,没有 B
完全已知并且当处理 B
, C
仍是不完整的类型。 comp.lang.c ++。moderated 中有类似的主题, a href =http://groups.google.com/group/comp.lang.c++/browse_frm/thread/562d5a77cf4c1f12/> comp.lang.c ++ 。
注意,如果你通过将它移动到成员函数定义来延迟使用,它可以工作,例如:
struct C:B < {
void f(){typedef typename C :: Asub Asub; }
};
您可以通过向上传递类型来解决问题:
template< class T,class Asub> struct B {/ * ... * /};
class C:B< C,int> {/ * ... * /};
...或者如果你需要传递更多的话, >
template< class T,class Traits> struct B {
void DoSomething(typename Traits :: Asub it){}
};
struct CTraits {
typedef int Asub;
};
struct C:B< C,CTraits> {
typedef CTraits :: Asub Asub;
};
The following code does not compile. I get an error message: error C2039: 'Asub' : is not a member of 'C'
Can someone help me to understand this?
Tried VS2008 & 2010 compiler.
template <class T>
class B
{
typedef int Asub;
public:
void DoSomething(typename T::Asub it)
{
}
};
class C : public B<C>
{
public:
typedef int Asub;
};
class A
{
public:
typedef int Asub;
};
int _tmain(int argc, _TCHAR* argv[])
{
C theThing;
theThing.DoSomething(C::Asub());
return 0;
}
You are being a bit unfair to the compiler here - C
is incomplete without B<C>
fully known and when processing B<C>
, C
is still an incomplete type. There are similar threads on comp.lang.c++.moderated and comp.lang.c++.
Note that it works if you delay the use by moving it into a member function definition, e.g.:
struct C : B<C> {
void f() { typedef typename C::Asub Asub; }
};
You could work around the problem by either passing the types explicitly upward:
template<class T, class Asub> struct B { /* ... */ };
class C : B<C, int> { /* ... */ };
... or by moving them to some traits class if you need to pass more:
template<class T, class Traits> struct B {
void DoSomething(typename Traits::Asub it) {}
};
struct CTraits {
typedef int Asub;
};
struct C : B<C, CTraits> {
typedef CTraits::Asub Asub;
};
这篇关于“继承”类型使用CRTP和typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!