误解可变参数模板函数
Misunderstanding variadic template functions
我不确定如何从我编写的可变参数模板函数中获得特定效果。下面是我写的函数。
template<typename ... T>
bool multiComparision(const char scope, T ... args) {
return (scope == (args || ...));
}
有人向我指出,尽管在我的代码的更大范围内没有产生任何错误,但这实际上执行了与我想要的不同的东西。
multiComparision('a', '1', '2', '3');
=>
return ('a' == ('1' || '2' || '3'));
我实际上打算让函数返回以下内容
multiComparision('a', '1', '2', '3');
=>
return ('a' == '1' || 'a' == '2' || 'a' == '3');
如何达到预期效果?
如何达到预期效果?
将相等比较表达式括在括号中:
template<typename ... T>
bool multiComparision(const char scope, T ... args) {
return ((scope == args) || ...);
}
godbolt.org 上的活生生的例子
C++14解决方案:
template<typename ... T>
constexpr bool multiComparision(const char scope, T ... args) {
bool result = false;
(void) std::initializer_list<int>{
((result = result || (scope == args)), 0)...
};
return result;
}
godbolt.org 上的活生生的例子
使用 C++11 和 C++14 时,您将需要重载multiComparision
。
bool multiComparision(const char scope) {
return false;
}
template <typename ... T>
bool multiComparision(const char scope, char arg1, T... args) {
return ( scope == arg1 || multiComparision(scope, args...));
}
看到它在 https://ideone.com/Z3fTAI 工作
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数