CRTP相關的編譯器錯誤我有相當簡單的,我想,問題大概CRTP,但我似乎無法找到一個答案。可能是因爲它太簡單了,沒有人想過要問它。我對這個概念很陌生,所以請不要太難過;)。上的typedef
下面是代碼(它的排序試圖做一些類似STL容器東西):如果我評論違規typedef typename _THelpee::T Th;
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;
,爲什麼它讓通過static_cast< _THelpee* > (this)->mVal
?我認爲,它有事情做與不能夠實例TDerived
何時實例THelper
,但沒有清晰的認識。請問有人能給出一個簡短的解釋和/或一些有關這裏發生的事情的參考嗎?謝謝。
編輯:刪除 '_T' 前綴。
標識符開始與[_和後跟大寫字母被保留(http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac -identifier/228797#228797)。 – Flexo
不要使用下劃線資本爲自己的標識符,這是禁止的。 –