如何在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)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我可以添加一个冗余的模板参数,但它会是多余的.
我也可以尝试使Bar成为模板函数,并将其专门用于U和V,但这不是我的代码,问题可能只会传播.
我可以创建一个CallBar除了调用Bar(false)和专门调用Bar(true)U和V之外什么都不做的函数.但是这个例子实际上有点过于简单了.布尔值在FooLogger中的多个位置使用,Bar有时甚至在?:conditionals 中调用函数(因此有多个s).
这里最好的事情是什么?
Ric*_*son 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);
...
}
Run Code Online (Sandbox Code Playgroud)
可能的解决方案std::is_same:
template <typename T>
void Foo(T t)
{
Bar(std::is_same<T, int>::value || std::is_same<T, char>::value);
}
Run Code Online (Sandbox Code Playgroud)