误解可变参数模板函数

Misunderstanding variadic template functions

本文关键字:函数 参数 变参 误解      更新时间:2023-10-16

我不确定如何从我编写的可变参数模板函数中获得特定效果。下面是我写的函数。

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 工作