我有这个类模板:
template<class... T>
class Test {
std::vector<TestCase*> test_cases;
public:
Test() {
// Here, for each T an instance should be added to test_cases.
test_cases.push_back((new T)...);
}
};
这对于一个模板参数工作正常,但对于多个参数我得到这个错误:
error: too many arguments to function call, expected 1, have 2
如何通过这种方式将可变参数模板与 new
一起使用?正确的语法是什么?
编辑:我认为我的问题不是很清楚。我想要的是:
Test<TestCase1, TestCase2, TestCase3>;
// The constructor will then be:
test_cases.push_back(new TestCase1);
test_cases.push_back(new TestCase2);
test_cases.push_back(new TestCase3);
我的编译器是带有此标志的 clang 163.7.1:-std=c++0x
。
最佳答案
vector::push_back
需要一个参数,因此您无法在函数调用中扩展可变参数模板。
我还为基类添加了一个模板参数(所有其他类都从中派生)。
这是 compiles 的东西.
struct base{};
struct d0 : base{};
struct d1 : base{};
struct d2 : base{};
#include <vector>
// termination condition for helper function
template <class T>
void add(std::vector<T*>&) {
}
// helper function
template <class T, class Head, class... Tail>
void add(std::vector<T*>& v) {
v.push_back(new Head());
add<T, Tail...>(v);
}
template <class T, class ... U>
class test
{
std::vector<T*> vec;
public:
test() {
add<T, U...>(vec);
}
};
int main()
{
test<base, d0,d1,d2> t;
}
关于c++ - 可变参数模板和新的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463753/