2012-06-28 53 views
0

我希望在模板類中有一個自定義方法 - 我將調用MyMethod - 只在Foo使用某些模板參數類型時調用Foo - ONLY (例如,當A是int且B是字符串時),否則,我不希望MyMethod存在於任何其他可能的Foo實例上。boost:enable_if在模板類中定義專用方法

這可能嗎?

例子:

template<class A, class B> 
class Foo 
{ 
    string MyMethod(whatever...); 
} 

升壓:enable_if可以幫助呢?

謝謝!

+0

如果您使用C++ 11,還有'std :: enable_if'。你應該看看SFINAE。 http://en.cppreference.com/w/cpp/types/enable_if –

回答

0

你在這裏真正想要的是專門化你的模板。在你的榜樣,你可以這樣寫:

template<> 
class Foo<int, string> 
{ 
    string MyMethod(whatever...); 
}; 

你也可以使用enable_if:

template<typename A, typename B> 
class Foo 
{ 
    typename boost::enable_if< 
      boost::mpl::and_< 
       boost::mpl::is_same<A, int>, 
       boost::mpl::is_same<B, string> 
      >, 
      string>::type MyMethod(whatever...){} 
}; 

如果沒有超載,你也可以使用static_assert:

template<typename A, typename B> 
class Foo 
{ 
    string MyMethod(whatever...) 
    { 
     static_assert(your condition here, "must validate condition"); 
     // method implementation follows 
    } 
}; 

這將產生當您嘗試調用MyMethod並且未設置條件時發生編譯錯誤。

+0

模板專業化的作品,但我將不得不復制任何其他 - 標準 - 美孚方法。 – codeJack

+1

@codeJack然後您可以隨時使用第二種方法。但是,SFINAE對於重載分辨率更重要。如果沒有重載,則可以使用static_assert,並且可以提供更好的錯誤消息。 – wendazhou

+0

有趣的是,如何在我的例子中使用靜態斷言? – codeJack