開發環境:VS2005(VC8)
以下代碼在VS2002上運行不了,據說VS2002(VC7)不完全支援偏特化,VS2003(VC7.1)就支援了。
問題提出:
一,已知類型T,U,在編譯階段如何知道T能否轉化成U。
template <class T, class U>
struct ConversionHelper
{
static long Test(...);//WQ註:C++中,不定參數已不需要“至少一個定參”了。
static short Test(U);
static T MakeT();
};
template <class T, class U>
struct Conversion
{
typedef ConversionHelper<T, U> H;
enum { exists = sizeof(short) == sizeof(H::Test(H::MakeT())) };
};
class A
{
public:
A()
{
TRACE("\r\nAr\n");
}
};
class B : public A
{
public:
B()
{
TRACE("\r\nBr\r\n");
}
};
測試代碼:
bool b1 = Conversion<B,A>::exists;
bool b2 = Conversion<A,B>::exists;
運行結果分別為true,false.
二,接上面的問題。如果T能轉化成U,則定義一個U類型的對象,否則定義T類型的變數。
template <int flag, typename T, typename U>
struct Select
{
typedef U Result;
};
template <typename T, typename U>
struct Select<0, T, U>
{
typedef T Result;
};
測試代碼:
Select<Conversion<B,A>::exists,B,A>::Result type;
type的類型是A;B不再繼承與A,則type類型是B。