如何根据模板参数更改值
How do I change a value based on a template parameter?
如何在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);
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 有根的二进制搜索树.保留与其父级的链接
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 菱形 传递叶类对象作为参数来代替根类
- "return-by-reference"或"pass-by-reference"参数何时与constexpr兼容?
- 试图编译一个c++代码与根(Cern)参数包括