![](/img/trans.png)
[英]How to specialize a class template for a tuple by using variadic template arguments?
[英]Using variadic template to create template class tuple
我正在尝试制作可变参数模板类postOffice
template <class... AllInputTypes>
class PostOffice {
public:
PostOffice(AllInputTypes&... akkUboytTypes)
: allInputMsgStorage(allInputTypes...) {}
...
protected:
std::tuple<StorageSlot<AllInputTypes>...> allInputMsgStorage; //TODO: Will this work?
}
带存储StorageSlot
template<class InputMsgType>
class StorageSlot {
public:
StorageSlot(InputMsgType& input)
: readFlag(false),
writeFlag(false),
storageField(input)
//TODO initialize timer with period, get period from CAN
{}
virtual ~StorageSlot();
InputMsgType storageField; //the field that it is being stored into
bool readFlag; //the flag that checks if it is being read into
bool writeFlag; //flag that checks if it is being written into
Timer StorageSlotTimer; //the timer that checks the read and write flag
};
所以在元组中,我试图初始化一个元组
StorageSlot<AllInputType1>, StorageSlot<AllInputType2>,...
等等
这样行吗? 我试过了
std::tuple<StorageSlot<AllInputTypes...>> allInputMsgStorage;
但这会在可变参数模板和单个模板存储插槽之间造成不匹配。 但是,我不确定
std::tuple<StorageSlot<AllInputTypes>...> allInputMsgStorage;
是完全定义的( StorageSlot
不是模板),更不用说产生正确的结果了。 我能想到完成这项工作的唯一原因是让StorageSlot<AllInputTypes>
直接发送到postOffice
并执行
std::tuple<AllInputTypeStorageSlots...> allInputMsgStorage;
这使得PostOffice
类的模板界面有点难看
那么,这项工作会成功吗?如果没有,我该如何工作呢?
总体概念是正确的-稍加修饰,即可为构造函数提供完美的转发,以提高效率。
此外,在StorageSlot中不需要虚拟析构函数-始终使用零规则,除非您将要使用动态多态性:
编译代码:
#include <tuple>
#include <string>
struct Timer
{};
template<class InputMsgType>
class StorageSlot {
public:
template<class ArgType>
StorageSlot(ArgType&& input)
: readFlag(false),
writeFlag(false),
storageField(std::forward<ArgType>(input))
//TODO initialize timer with period, get period from CAN
{}
InputMsgType storageField; //the field that it is being stored into
bool readFlag; //the flag that checks if it is being read into
bool writeFlag; //flag that checks if it is being written into
Timer StorageSlotTimer; //the timer that checks the read and write flag
};
template <class... AllInputTypes>
class PostOffice {
public:
//
// note - perfect forwarding
//
template<class...Args>
PostOffice(Args&&... allInputTypes)
: allInputMsgStorage(std::forward<Args>(allInputTypes)...)
{
}
protected:
std::tuple<StorageSlot<AllInputTypes>...> allInputMsgStorage; //TODO: Will this work? - yes
};
int main()
{
PostOffice<int, double, std::string> po(10, 20.1, "foo");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.