gpt4 book ai didi

c++ - 使用可变参数模板创建模板类元组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:12 24 4
gpt4 key购买 nike

我正在尝试制作可变参数模板类 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");

}

关于c++ - 使用可变参数模板创建模板类元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42553076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com