我想我有一个相当简单的关于CRTP的问题,但我似乎找不到答案。大概是因为太简单了,没有人想过要问。我是这个概念的新手,所以,请不要笑得太厉害;)。
这是代码(这是一种类似于 STL 容器的尝试):
template< typename tT >
struct TBase
{
typedef tT T;
};
template< typename tTBase >
struct TTraitsBase
{
typedef typename tTBase::T T;
};
template< typename tTHelpee, typename tTTraits >
struct THelper
{
typedef typename tTTraits::T T;
typedef typename tTHelpee::T Th; /* This generates a compiler error:
'T' not being a member of TDerived<tT> */
T Foo( void )
{
return static_cast< tTHelpee* > ( this )->mVal;
}
};
template< typename tT >
struct TDerived : TBase< tT > , THelper< TDerived< tT > , TTraitsBase< TBase< tT > > >
{
using TBase< tT >::T;
T mVal;
};
int main()
{
TDerived< int >::T lTmp = -1;
TDerived< int > lObj;
lObj.mVal = -1;
std::cout << lObj.Foo() << std::endl;
return 0;
}
如果我评论有问题,一切都会编译typedef typename _THelpee::T Th;
。这让我感到困惑:如果编译器不喜欢typedef typename _THelpee::T Th;
,为什么它会通过static_cast< _THelpee* > ( this )->mVal
?我认为,这与实例化THelper
时无法实例化有关TDerived
,但没有清楚的理解。有人可以就这里发生的事情给出一个简短的解释和/或一些参考吗?谢谢你。
编辑:删除 '_T' 前缀。