2009-04-30 12 views
1

以下模板將決定T是否是用g ++抽象的。isAbstract template and visual studio

/** 
    isAbstract<T>::result is 1 if T is abstract, 0 if otherwise. 
*/ 
template<typename T> 
class isAbstract 
{ 
    class No { }; 
    class Yes { No no[3]; }; 

    template<class U> static No test(U (*)[1]); // not defined 
    template<class U> static Yes test(...); // not defined 

public: 
    enum { result = sizeof(isAbstract<T>::template test<T>(0)) == sizeof(Yes) }; 
}; 

例如: struct myClass2 {virtual void f(){}}; struct myClass1 {virtual void f()= 0; };

bool twoAbstract = isAbstract<myClass2>::result; 
bool oneAbstract = isAbstract<myClass1>::result; 

然而,在Visual Studio 9.0失敗,出現錯誤:

error C2784: 'AiLive::isAbstract<T>::No AiLive::isAbstract<T>::test(U (*)[1])' : could not deduce template argument for 'U (*)[1]' from 'myClass2' 

有沒有人有問題是什麼,如何解決這一問題的想法?

MSDN報告他們現在有一個is_abstract級別,因爲VS2008是TR1的一部分(在標頭type_traits內)。但是,它似乎從我的安裝中丟失。

PS。由於長期無聊的原因,我無法通過Boost重新實現。

更新

另外,試圖替換,

template<class U> static No test(U (*)[1]); 

與每個,

template<class U> static No test(U (*x)[1]); 
template<class U> static No test(U (*)()); 
template<class U> static No test(U (*x)()); 

template <typename U> 
struct U2 : public U 
{ 
    U2(U*) {} 
}; 

// Match if I can make a U2 
template <typename U> static No test(U2<U> x ); 

// Match if I can make a U2 
template <typename U> static No test(U2<T> x ); 

沒有運氣 - 都說模板參數不能推導出U.

+0

我認爲代碼很好,懷疑VC++的錯誤。也許試試這個:template static沒有測試(U(*)());或者參數的名稱(可能是因爲參數沒有名字而導致窒息?)。 – 2009-05-01 00:08:44

+0

謝謝。試過這些,但工作原理是一樣的。 (我已經在上面添加了這些案例和一個額外的案例)。 – user48956 2009-05-01 01:26:48

+0

嗯,只是看起來更深。我的建議U(*)()似乎不起作用,'因爲具有抽象返回類型的函數類型不是無效的。這是不可能有這樣的功能。導致一個「真正的」編譯時間錯誤與comeau :) – 2009-05-04 13:09:00

回答

1

該作品我在VC9:

template<typename T> 
class isAbstract 
{ 
    class No { }; 
    class Yes { No no[3]; }; 

    template<class U> static No test(U (*)[1]); // not defined 
    template<class U> static Yes test(...); // not defined 

public: 
    enum { result = sizeof(test<T>(0)) == sizeof(Yes) }; 
}; 

通知我剛剛從通話中刪除isAbstract<T>::test

0

不知道,因爲我已經記做C++一段時間,但你可以使用

template< typename T, typename U> 
class isAbstract 
{ 
    class No { }; 
    class Yes { No no[3]; }; 

    template<class U> static No test(U (*)[1]); // not defined 
    template<class U> static Yes test(...); // not defined 

public: 
    enum { result = sizeof(isAbstract<T>::template test<T>(0)) == sizeof(Yes) }; 
}; 


bool twoAbstract = isAbstract<myClass2, SomeTypeU>::result; 
相關問題