2

如何在 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,但这不是我的代码,问题可能只会传播。

我可以创建一个函数,除了调用和专门化它来调用U 和 VCallBar之外什么都不做。但是这个例子实际上有点过于简单了。布尔值在 FooLogger 中的多个地方使用,有时用于函数调用(因此有多个s),有时甚至在 ?: 条件中。Bar(false)Bar(true)Bar

在这里做的最好的事情是什么?

4

2 回答 2

10

惯用的解决方案是使用特征:

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);
  ...
}
于 2013-06-05T09:18:25.903 回答
5

一个可能的解决方案std::is_same

template <typename T>
void Foo(T t)
{
    Bar(std::is_same<T, int>::value || std::is_same<T, char>::value);
}
于 2013-06-05T09:20:57.513 回答