將C++模板類的參數包隱藏到std::tuple

Modern C++引入了可變模板以及模板參數包,以下。ios

template<typename... Args>
class MultiArgs{};

能夠使用std::tuple將參數包隱藏起來,以下。c++

template<typename... Args>
class MultiArgs{
using Tuple = std::tuple<Args...>;
};

那麼,怎麼取出某個參數類型呢?好比,第0個,以及最後一個參數。code

能夠藉助std::tuple_element來實現。代碼以下。element

template<typename... Args>
class MultiArgs{
using Tuple = std::tuple<Args...>;

template<std::size_t N>
using Type = typename std::tuple_element<N,Tuple>::type;
};

同時,咱們能夠利用sizeof...來獲取參數包的個數。string

static constexpr auto Size = sizeof...(Args);

所以,若是須要取出第0個和最後一個參數,能夠使用如下代碼。io

template<typename... Args>
class MultiArgs{
using Tuple = std::tuple<Args...>;
static constexpr auto Size = sizeof...(Args);

template<std::size_t N>
using Type = typename std::tuple_element<N,Tuple>::type;

using FirstArg = Type<0>;
using LastArg = Type<Size-1>;
};

若是上面的例子只能取出第0個和最後有一個參數,那麼若是用戶想要取出某個參數呢?完整代碼以下。ast

#include <iostream>
#include <tuple>
#include <string>

template<typename... Args>
class MultiArgs{
public: 
using Tuple = std::tuple<Args...>;
static constexpr auto Size = sizeof...(Args);

template<std::size_t N>
using Type = typename std::tuple_element<N,Tuple>::type;

using FirstArg = Type<0>;
using LastArg = Type<Size-1>;

MultiArgs(){}
~MultiArgs(){}

void PrintFirstArgType(){
std::cout<<"The first arg type:"<<typeid(FirstArg).name()<<std::endl;
}

void PrintLastArgType(){
std::cout<<"The last arg type:"<<typeid(LastArg).name()<<std::endl;
}

template<std::size_t N>
void PrintType(){
std::cout<<"The arg at index:"<<N<<" type:"<<typeid(Type<N>).name()<<std::endl;
}
};

int main(){
MultiArgs<int,double,float,std::string>::Type<3> my_string;
my_string = "hello world";
std::cout<<"my_string:"<<my_string<<std::endl;

MultiArgs<int,double,float,std::string> multi_args;
multi_args.PrintFirstArgType();
multi_args.PrintType<1>();
multi_args.PrintType<2>();
multi_args.PrintLastArgType();

return 0;
}
相關文章
相關標籤/搜索