2
votes

I have a class that takes a bool template parameter. The class will have several methods which I need to specialize on the class bool template parameter. Is there a way of doing this without specialising the whole class itself?

Foo::bar() below is an example of what I mean, it does not work since std::is_same works with types and not values

Thanks.

template<bool Mode>
class Foo
{   
public:
template<bool M=Mode, typename std::enable_if<std::is_same<M,true>::value>::type * = 0>
void bar()
{
    std::cout << "true" << std::endl;
}

template<bool M=Mode, typename std::enable_if<std::is_same<M,false>::value>::type * = 0>
void bar()
{
    std::cout << "false" << std::endl;
}
3
std::is_same compares types. M is a constant, true and false are values, i.e. they're not types. - dyp

3 Answers

4
votes

You don't need to use std::is_same. std::enable_if already takes a boolean parameter:

template <bool Mode>
class Foo
{   
    public:
        template <bool M = Mode, typename std::enable_if<M>::type* = nullptr>
        void bar()
        {
            std::cout << "true" << std::endl;
        }

        template <bool M = Mode, typename std::enable_if<!M>::type* = nullptr>
        void bar()
        {
            std::cout << "false" << std::endl;
        }
};

Here is a demo.

9
votes

Maybe I am missing something, but why not use plain good old specialization?

template <bool M>
struct base_template {
   void bar();
};

template <>
inline void base_template<true>::bar() { std::cout << "true\n"; }
template <>
inline void base_template<false>::bar() { std::cout << "false\n"; }
2
votes

You're on the right track. Just use the template parameter directly:

template<bool M=Mode, typename std::enable_if<M == true>::type * = 0>
void bar()                                 //^^^^^^^^^^
{
    std::cout << "true" << std::endl;
}