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

时间:2015-06-30 10:53:23

标签: 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) 
   {
   }
};

我使用如下:

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);

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

上面的@TartanLlama在visual studio 13(C ++或arduino dev环境)中对我不起作用。

经过一些试验后发现这个有效。

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