0

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!!

codeJack
  • 2,423
  • 5
  • 24
  • 31
  • There's also `std::enable_if` if you are using C++11. You should look into SFINAE. http://en.cppreference.com/w/cpp/types/enable_if – Tony The Lion Jun 28 '12 at 10:34

1 Answers1

0

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.

wendazhou
  • 295
  • 2
  • 10
  • template specialization works, but I would have to duplicate any other - standard - Foo method. – codeJack Jun 28 '12 at 11:37
  • 1
    @codeJack Then you can always use the second method. However, SFINAE is more important for overload resolution. If there are no overloads, you can just use static_assert and you can provide a better error message. – wendazhou Jun 28 '12 at 15:09
  • interesting, how would you use static assert in my example ? – codeJack Jun 29 '12 at 08:19