我正在尝试制作可变参数模板类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
类的模板接口(interface)有点难看那么,这项工作会成功吗?如果没有,我该如何工作呢?
最佳答案
总体概念是正确的-稍加修饰,即可为构造函数提供完美的转发,以提高效率。
另外,在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");
}
关于c++ - 使用可变参数模板创建模板类元组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42553076/