C++基于模板的派生类和变量参数的构造函数

RB1*_*987 0 c++ inheritance constructor ellipsis

经过很长一段时间用c ++开发,所以请忍受我对语言的无知.在我的设计中,我有派生类,基类是使用模板传递的.

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

我使用如下:

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

这里可以使用省略号吗?所以最终结果会像这样..

Controller<ValueDriven, Eth_Driver> ctn(1, 2, 3, 2, 3, 8);
Run Code Online (Sandbox Code Playgroud)

我尝试了省略号,但无法找到将椭圆从Controller传递到SwitchType的方法.

注意*将此用于arduino平台.所以远离std :: lib

Tar*_*ama 5

您可以将构造函数转换为可变参数模板:

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

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

Controller<ValueDriven, Eth_Driver> ctn(1, 2, 3, 2, 3, 8);
//                                            ^ size
//                                               ^^^^^^^ forwarded
Run Code Online (Sandbox Code Playgroud)