How do I do the following in C++:
template <typename T>
void Foo(T t)
{
...
call Bar(true) if T is of some specific type U or V
call Bar(false) otherwise
...
}
void Bar(bool b)
{
...
}
I could add a redundant template parameter but it would be, well..., redundant.
I could also try to make Bar a template function and specialize it for U and V but that is not my code and the problem would probably just propagate.
I could create a function CallBar that does nothing but to call Bar(false) and specialize it to call Bar(true) for U and V. But the example is actually a bit oversimplified here. The boolean is used in multiple places in the FooLogger sometimes in calls to functions (so there are multiple Bars) sometimes even in ?: conditionals.
What is the best thing to do here?
The idiomatic solution would be to use traits:
template <typename T>
struct BarTraits {
static const bool value = false;
};
template <>
struct BarTraits<U> {
static const bool value = true;
};
template <>
struct BarTraits<V> {
static const bool value = true;
};
template <typename T>
void Foo(T t)
{
...
Bar(BarTraits<T>::value);
...
}
A possible solution using std::is_same:
template <typename T>
void Foo(T t)
{
Bar(std::is_same<T, int>::value || std::is_same<T, char>::value);
}
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