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

C++ Constructors of template based derived class & variable arguments

本文关键字:变量 参数 构造函数 派生 于模板 C++      更新时间:2023-10-16

在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

您可以将构造函数制作成一个可变模板:

//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
上面的

@TartanLlama在visual studio 13(C++或arduino开发环境)中对我不起作用。

经过一些试验,发现这是有效的。

class test1
{
public:
    test1(int argc, ...)
    {
        printf("Size: %dn", 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("nnSize @Derived: %dn", argc);
        va_list args;
        va_start(args, argc);
        for (int i = 0; i < argc; i++)
        {
            printf("Values @Derived: %dn", 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);
    }
}