我想實例化一個可變參數模板類Store<TArgs...>
,它對於TArgs...
包中的每種類型都有一個std::vector
。可變參數模板類參數容器實例
template<typename... TArgs> class Store {
// obviously not valid code
// assuming each type of TArgs... has a `unsigned int` id that can be
// retrieved with getId<T>()
std::array<sizeof...(TArgs), std::vector<TArgs...>> bags;
template<typename T> void add(T mValue) {
bags[getId<T>()].push_back(mValue);
}
template<typename T> std::vector<T>& get() {
return bags[getId<T>()];
}
};
比方說,我有一個Store<int, float, double>
。我在編譯時顯然知道它將能夠存儲int
,float
和double
值。
我可以使用模板特:
template<> class Store<int, float, double> {
std::vector<int> vi;
std::vector<float> vf;
std::vector<double> vd;
template<typename T> void add(T);
template<> void add<int>(int mValue) { vi.push_back(mValue); }
template<> void add<float>(float mValue) { vf.push_back(mValue); }
template<> void add<double>(double mValue) { vd.push_back(mValue); }
// ...
};
...但這需要手寫的類型每個可能的組合,並且不會與用戶定義類型的工作。
我相信編譯器知道使用可變參數模板生成像Store<int, float, double>
這樣的類所需的一切 - 有沒有一種方法可以真正表達這種意圖?
你需要一個'std :: tuple'來做到這一點,'std :: vector'不適合。 –
這裏>> std :: array>',模板參數的順序是錯誤的。它應該是'std :: array ',而不是'std :: array '。另外,我認爲你需要'std :: tuple',而不是'std :: vector'(我不確定)。 –
Nawaz