问题
I would like to have a custom method - I will call MyMethod - in a templated class - I will call Foo - ONLY when Foo has been instanciated with certain template parameters types (eg. when A is int and B is string), otherwise, I don't want MyMethod to exist at all on any other possible Foo instance.
Is that possible ?
Example:
template<class A, class B>
class Foo
{
string MyMethod(whatever...);
}
boost:enable_if can help there ?
Thanks!!
回答1:
What you really want here is to specialize your template. In your example, you would write:
template<>
class Foo<int, string>
{
string MyMethod(whatever...);
};
you can also use 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...){}
};
if there are no overloads, you can also use static_assert:
template<typename A, typename B>
class Foo
{
string MyMethod(whatever...)
{
static_assert(your condition here, "must validate condition");
// method implementation follows
}
};
this will produce a compile error when you try to invoke MyMethod and the condition is not set.
来源:https://stackoverflow.com/questions/11242445/boostenable-if-to-define-a-dedicated-method-in-a-templated-class