2010-07-08 47 views
3

可能重複:
Possible for C++ template to check for a function’s existence?確定一個班有一個特定的成員嗎?

我試圖確定閹類型具有一定的成員。這是我的嘗試:

template <typename T,typename U=void> 
class HasX 
{ 
public: 
    static const bool Result=false; 
}; 

template <typename T> 
class HasX<T,typename enable_if_c<(sizeof(&T::X)>0)>::type> 
{ 
public: 
    static const bool Result=true; 
}; 


struct A 
{ 
    int X(); 
}; 

struct B 
{ 
    int Y(); 
}; 


int main() 
{ 
    cout<<HasX<A>::Result<<endl; // 1 
    cout<<HasX<B>::Result<<endl; // 0 
} 

它實際上編譯和工作在海灣合作委員會,但VC在instanciation的點給出​​。

代碼有問題,還有其他方法可以做到嗎?

+1

重複[可能爲C++模板檢查函數的存在?](http://stackoverflow.com/questions/257288/possible-for-c-template-to-check-for-a-functions-existence ),也許看看[SFINAE來檢查繼承的成員函數](http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions)。 – 2010-07-08 00:41:56

回答

6

確實存在:從here

typedef char (&no_tag)[1]; 
typedef char (&yes_tag)[2]; 

template < typename T, void (T::*)() > struct ptmf_helper {}; 
template< typename T > no_tag has_member_foo_helper(...); 

template< typename T > 
yes_tag has_member_foo_helper(ptmf_helper<T, &T::foo>* p); 

template< typename T > 
struct has_member_foo 
{ 
    BOOST_STATIC_CONSTANT(bool 
     , value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag) 
     ); 
}; 

struct my {}; 
struct her { void foo(); }; 

int main() 
{ 
    BOOST_STATIC_ASSERT(!has_member_foo<my>::value); 
    BOOST_STATIC_ASSERT(has_member_foo<her>::value); 

    return 0; 
} 

複製粘貼。

編輯:更新符合AFAIK的代碼。還要注意,你必須知道你正在檢查的方法的返回類型的參數。

+0

由於某種原因無法在VC上工作。在'has_member_foo_helper(int,void(T :: *)()=&T :: foo)'給出'錯誤C2065:'foo':未聲明的標識符';' – uj2 2010-07-08 00:54:52

+0

@ uj2:我更新了代碼,再試一次!它在GCC上編譯。 – Staffan 2010-07-08 01:04:34

相關問題