Pro*_*ysX 1 c++ templates variadic-templates
我有一个通用类Test<T>,我想要一个函数test_function(),它具有可变数量的Test<T>对象输入参数,带有.... 在函数中,我想遍历所有参数。参数的泛型类型T可以不同。像这样的东西:
template <typename T> class Test {
private:
T value = (T)0;
int test = 1;
public:
Test() = default;
int get_test() {
return test;
}
}
template <typename T> void test_function(const Test<T> tests...) {
for(auto test : tests) {
cout << test.get_test() << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
编译时,我收到错误:
error C3520: "T": Parameter pack must be extended in this context
error C3520: "tests": Parameter pack must be extended in this context
error C3312: no callable 'begin' function found for type 'unknown-type'
error C3312: no callable 'end' function found for type 'unknown-type'
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
编辑:是否可以在扩展中有一个计数器?
编辑 2:我用计数器想通了:
template <typename ...T> void test_function(const Test<T> ...tests) {
int i=0;
((cout << tests.get_test() << ", counter = " << i++ << endl), ...);
}
Run Code Online (Sandbox Code Playgroud)
这里有多个问题。
首先,正确的可变参数模板函数声明应该是:
template <typename ...T> void test_function(const Test<T> ...tests)
Run Code Online (Sandbox Code Playgroud)
但这并不能解决所有问题。第一个是所有参数都是const对象,因此类方法也必须是 const 类成员:
int get_test() const {
Run Code Online (Sandbox Code Playgroud)
最后:
for(auto test : tests) {
Run Code Online (Sandbox Code Playgroud)
tests不是一个可以进行范围迭代的容器,就像一个向量。它是一个参数包,需要像这样扩展:
((cout << tests.get_test()), ...);
Run Code Online (Sandbox Code Playgroud)
用 gcc 11 测试:
#include <iostream>
using namespace std;
template <typename T> class Test {
private:
T value = (T)0;
int test = 1;
public:
Test() = default;
int get_test() const {
return test;
}
};
template <typename ...T> void test_function(const Test<T> ...tests) {
((cout << tests.get_test()), ...);
}
void foo()
{
test_function(Test<int>{}, Test<char>{});
}
Run Code Online (Sandbox Code Playgroud)