我不确定如何从我编写的可变参数模板函数中获得特定效果。下面是我编写的函数。
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) || ...);
}
live example on 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;
}
live example on godbolt.org
关于c++ - 对可变参数模板功能的误解,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59036765/