2015-06-30 61 views
0

长时间在C++中开发,所以请忍受我对语言的无知.. 在我的设计中,我有派生类,为此使用模板传递基类。基于模板的派生类和可变参数的C++构造函数

template <class DeviceType, class SwitchType> class Controller : public SwitchType 
{ 
public: 
/* Constructor */ 
Controller(byte ID, byte NumberOfDevices, int size, int data[]) : SwitchType(size, data) 
    { 
    } 
}; 

我使用这个如下:

Controller <ValueDriven, Eth_Driver> ctn(1, 2, 3, new int[3]{2, 3, 8}); 

是否有可能在这里使用省略号?从而使最终的结果会喜欢这个..

Controller<ValueDriven, Eth_Driver> ctn(1, 2, 3, 2, 3, 8); 

我试过椭圆,但不可能找到一种方法,从控制器通过椭圆SwitchType。

注*将此用于arduino平台。因此,从性病避而远:: lib中

+1

我觉得被泄露的地方一些内存... – ikh

+0

有泄漏,如果数据没有被删除的存在。 – RB1987

+0

你为什么在第一时间打电话给'new'?你可以在编译时获得所有信息。 – JorenHeit

回答

5

你可以让你的构造为variadic template

//take any number of args 
template <typename... Args> 
Controller(byte ID, byte NumberOfDevices, int size, Args&&... data) 
    : SwitchType(size,std::forward<Args>(data)...) 
{ 
} 

现在你可以这样调用构造函数:

Controller<ValueDriven, Eth_Driver> ctn(1, 2, 3, 2, 3, 8); 
//           ^size 
//            ^^^^^^^ forwarded 
+0

不错,尽管你会遇到将这些值存储在某个地方的问题,并且他可能必须不使用'std :: forward',或者自己实现它。 – JorenHeit

0

@TartanLlama以上没有工作对于我在Visual Studio 13(C++或Arduino开发环境)中。

经过一些试验发现这个工作。

class test1 
{ 
public: 
    test1(int argc, ...) 
    { 

     printf("Size: %d\n", argc); 
     va_list list; 
     va_start(list, argc); 
     for (int i = 0; i < argc; i++) 
     { 
      printf("Values: %d \n", va_arg(list, int)); 
     } 
     va_end(list); 
    } 
}; 

class test2 : public test1 
{ 
public: 

    template<typename... Values> test2(int val, int argc, Values... data) : test1(argc, data...) 
    { 
     printf("\n\nSize @Derived: %d\n", argc); 
     va_list args; 
     va_start(args, argc); 
     for (int i = 0; i < argc; i++) 
     { 
      printf("Values @Derived: %d\n", va_arg(args, int)); 
     } 
     va_end(args); 
    } 
}; 

void setup() 
{ 

    test2(2090, 3, 30, 40, 50); 
} 

void loop() 
{ 

} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    setup(); 
    while (1) 
    { 
     loop(); 
     Sleep(100); 
    } 
} 
相关问题