c++ - 可变参数模板和新的

标签 c++ c++11 variadic-templates

我有这个类模板:

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/

相关文章:

c++ - 如何验证字符串是否是 C++ 中的有效 IPv4 地址?

c++ - c++中列表的接口(interface)

c++ - std::get 在右值引用元组上的行为是否危险?

c++ - 调用实际对象的方法而不是父类

c++ - 明确指定的模板参数包

c++ - 匹配多个组的正则表达式

c++ - 为什么(如果是这样的话)标准说用 memcpy 复制未初始化的内存是 UB?

c++ - 无法在函数模板中使用 lambda 函数

c++ - 仅为特定模板类启用模板

c++ - 模板包包