如何根据模板参数更改值

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

本文关键字:参数 何根      更新时间:2023-10-16

如何在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)
{
  ...
}

我可以添加一个冗余的模板参数,但是它会…多余的。

我也可以尝试使Bar成为模板函数,并为U和V专门化,但这不是我的代码,问题可能会传播。

我可以创建一个函数CallBar,它只调用Bar(false),并将其特化为为U和v调用Bar(true),但这里的示例实际上有点过于简化了。布尔值在FooLogger的多个地方使用,有时在调用函数(因此有多个Bar)中,有时甚至在?:条件中。

这里最好的做法是什么?

惯用的解决方案是使用trait:

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

使用std::is_same:

template <typename T>
void Foo(T t)
{
    Bar(std::is_same<T, int>::value || std::is_same<T, char>::value);
}