Sarien
Sarien

Reputation: 6982

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

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?

Upvotes: 3

Views: 514

Answers (2)

hmjd
hmjd

Reputation: 121971

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);
}

Upvotes: 6

Rick Yorgason
Rick Yorgason

Reputation: 1666

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);
  ...
}

Upvotes: 12

Related Questions