Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ class member function specialization on bool values

Tags:

c++

c++11

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;
}
like image 200
MK. Avatar asked Feb 23 '26 12:02

MK.


2 Answers

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"; }
like image 115
David Rodríguez - dribeas Avatar answered Feb 26 '26 01:02

David Rodríguez - dribeas


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.

like image 43
David G Avatar answered Feb 26 '26 00:02

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!