我试图制作一个可变参数模板类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;
但是这会在可变参数模板和单个模板存储槽之间产生不匹配。但是,我不确定IF
std::tuple<StorageSlot<AllInputTypes>...> allInputMsgStorage;
是根本定义的(StorageSlot
不是模板),更不用说产生正确的结果了。我能想到这项工作的唯一原因是让StorageSlot<AllInputTypes>
直接发送到postOffice
,然后执行
std::tuple<AllInputTypeStorageSlots...> allInputMsgStorage;
使PostOffice
类的模板接口有点丑陋
这样做会有效,如果没有,我怎么能让它发挥作用呢?
答案 0 :(得分:0)
一般概念是正确的 - 稍微改进一下,构造函数可以得到完美的转发以提高效率。
此外,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");
}