【发布时间】:2018-07-30 12:11:17
【问题描述】:
我正在编写由单一类型参数化的模板函数,并且具有可变数量的相同类型(不是不同类型)的参数。它应该检查第一个值是否在其余值中。我想这样写:
#include <unordered_set>
template <typename T>
static bool value_in(T val, T vals...) {
// compiles, but uses only vals[0]:
const std::unordered_set<T> allowed {vals};
// error: pack expansion does not contain any unexpanded parameter packs:
// const std::unordered_set<T> allowed {vals...};
return allowed.find(val) != allowed.end();
}
// usage
enum class Enumeration {one, two, three};
int main () {
// should return true -> 0
return value_in(Enumeration::two,
Enumeration::one,
Enumeration::two) ? 0 : 1;
}
我预计第二个可以工作,但它没有编译,因为
test.cpp: In function ‘bool value_in(T, T, ...)’:
test.cpp:7:46: error: expansion pattern ‘vals’ contains no argument packs
我看到的是“(T, T, ...)”而不是“(T, T...)”,所以我可能搞砸了函数声明并以 C 风格的可变参数函数结束。
如何编写将接受任意数量的相同类型参数的声明?
【问题讨论】:
-
必须是 C++11 还是你也接受 C++14/C++17 的答案?
-
@max66 我需要它在 c++14 中工作,但即使使用 c++20,我也会支持任何答案 :-) 我只是认为 c++11 中存在所有必要的功能
-
This 是关于该主题的有用论文。
标签: c++ templates c++14 variadic-templates variadic-functions