了解test_function(Test<T>…)的C++可变数量的输入参数

我有一个通用类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;
    }
}

编译时,我收到错误:

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'

我究竟做错了什么?

编辑:是否可以在扩展中有一个计数器?

编辑 2:我用计数器想通了:

template <typename ...T> void test_function(const Test<T> ...tests) {
    int i=0;
    ((cout << tests.get_test() << ", counter = " << i++ << endl), ...);
}

回答

这里有多个问题。

首先,正确的可变参数模板函数声明应该是:

template <typename ...T> void test_function(const Test<T> ...tests)

但这并不能解决所有问题。第一个是所有参数都是const对象,因此类方法也必须是 const 类成员:

int get_test() const {

最后:

for(auto test : tests) {

tests不是一个可以进行范围迭代的容器,就像一个向量。它是一个参数包,需要像这样扩展:

((cout << tests.get_test()), ...);

用 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>{});
}


以上是了解test_function(Test&lt;T&gt;…)的C++可变数量的输入参数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>