將類型列表作爲可變參數模板參數,可以非常容易地對它們執行任意類型的操作,從而獲得修改後的類型的元組。例如。包裝與定製包裝類每一個元素,一個可以這樣做:修改元組元素的類型
template<typename T> class Wrapper {};
template<typename ...Values>
using WrappedValues = std::tuple<Wrapper<Values>...>;
using NewTuple = WrappedValues<int, std::string, char>;
static_assert(std::is_same<NewTuple, std::tuple<Wrapper<int>, Wrapper<std::string>, Wrapper<char>>>::value, "");
如何做同樣的,有性病的專業化::元組「輸入」的時候?例如。應該放置什麼而不是「???」做下面的代碼可編譯:
template<typename T> class Wrapper {};
template<typename Tuple>
using WrappedTupleElements = ???;
using NewTuple = WrappedTupleElements<std::tuple<int, std::string, char>>;
static_assert(std::is_same<NewTuple, std::tuple<Wrapper<int>, Wrapper<std::string>, Wrapper<char>>>::value, "");
我知道訪問類型使用std::tuple_element
和遞歸模板實例化的元組元素的可能性,但我不知道如何收集這種方式創建類型爲一個元組。
首選是純C++ 14答案,但也歡迎使用C++ 17,廣泛使用的TSes或外部庫(如boost)的提議。
死容易......我無法想象,我沒有想到這一點。謝謝! –