C++ 基于模板的派生类和变量参数的构造函数
C++ Constructors of template based derived class & variable arguments
在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);
}
}
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 存储稍后要转发的变量参数
- 包括一个类来定义全局变量参数 c++ :(
- 可变参数模板类的构造函数无法接受变量参数
- 变量参数列表 后面的'const std::string&'弄乱了堆栈
- 变量参数崩溃的 C 函数
- 如何使用变量参数化类型?C++
- 使用参数包分配具有变量参数的函数指针
- 参考变量参数与本地参考变量
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 如何基于模板变量参数多次扩展语句
- gmock一种接受变量参数的方法
- 使用变量参数列表与向量(C )的原因
- lambda 中的变量参数作为函数指针
- C 变量参数错误
- 带有变量参数列表的c++11 lambda函数
- 变量参数
- std::函数带有C变量参数,而不是模板变量参数