Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a value based on a template parameter?

Tags:

c++

templates

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?

like image 742
Sarien Avatar asked Mar 12 '26 16:03

Sarien


2 Answers

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);
  ...
}
like image 165
Rick Yorgason Avatar answered Mar 14 '26 04:03

Rick Yorgason


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);
}
like image 39
hmjd Avatar answered Mar 14 '26 06:03

hmjd



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!