【问题标题】:C++ Constructors of template based derived class & variable arguments基于模板的派生类和变量参数的 C++ 构造函数
【发布时间】:2015-09-17 03:12:43
【问题描述】:

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

【问题讨论】:

  • 我感觉某处有一些内存泄漏...
  • 是的,如果不删除数据,则存在泄漏。
  • 你为什么打电话给new?您在编译时拥有所有信息。
  • SwitchType 是如何构造的?您需要将这些值存储在某处,还是立即在构造函数中处理它们?
  • 每个 Switch 类型都使用数据初始化一些值,最后删除数据。我在想..不同的 SwitchTypes 必须有相似的构造函数,然后用户可以在实例化与此控制器关联的开关时选择。 *关于新的,不知道是否有其他方法可以传递一个常量数组。

标签: c++ inheritance constructor ellipsis


【解决方案1】:

你可以把你的构造函数变成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

【讨论】:

  • 不错的一个,虽然你会遇到将这些值存储在某个地方的问题,而且他可能不得不没有std::forward,或者自己实现它。
【解决方案2】:

上面的@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);
    }
}

【讨论】:

    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 2021-02-14
    • 2011-06-04
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多