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;
}
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"; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With