2017-03-02 53 views
2

我试图使一个可变参数模板类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类还挺难看

所以将这项工作的模板接口,并如果没有,我怎么能得到这个工作?

+2

你有没有遇到任何编译或运行程序时出现问题?看起来这应该很好。 – TartanLlama

+0

'StorageSlot'当然是一个模板。 'StorageSlot '将会扩展得很好。 –

+0

它编译,但我还没有找到一种方法来测试这是否给出正确的行为。但我主要关心编译器如何解释'std :: tuple ...> allInputMsgStorage;'。编译器如何确定'...'引用可变参数'AllInputTypes',并且它应该为每个StorageSlot元组成员提供可变参数模板的1个元素? –

回答

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"); 

} 
相关问题