对可变参数模板函数的误解
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'));
我实际上打算将此功能用于 return 以下
multiComparision('a', '1', '2', '3');
=>
return ('a' == '1' || 'a' == '2' || 'a' == '3');
怎样才能达到想要的效果?
How can I achieve the desired effect?
将相等比较表达式括在括号中:
template<typename ... T>
bool multiComparision(const char scope, T ... args) {
return ((scope == args) || ...);
}
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;
}
使用 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...));
}
查看它的工作情况
我不确定如何通过我编写的可变参数模板函数实现特定效果。下面是我写的函数。
template<typename ... T>
bool multiComparision(const char scope, T ... args) {
return (scope == (args || ...));
}
有人向我指出,这实际上执行了一些与我想要的不同的事情,尽管在我的代码的更大范围内没有产生任何错误。
multiComparision('a', '1', '2', '3');
=>
return ('a' == ('1' || '2' || '3'));
我实际上打算将此功能用于 return 以下
multiComparision('a', '1', '2', '3');
=>
return ('a' == '1' || 'a' == '2' || 'a' == '3');
怎样才能达到想要的效果?
How can I achieve the desired effect?
将相等比较表达式括在括号中:
template<typename ... T>
bool multiComparision(const char scope, T ... args) {
return ((scope == args) || ...);
}
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;
}
使用 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...));
}
查看它的工作情况