你在這裏真正想要的是專門化你的模板。在你的榜樣,你可以這樣寫:
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並且未設置條件時發生編譯錯誤。
如果您使用C++ 11,還有'std :: enable_if'。你應該看看SFINAE。 http://en.cppreference.com/w/cpp/types/enable_if –