可变参数模板代码实践,发给大家共勉!
#include <iostream>
#include <typeinfo>
#include <tuple>
#include <algorithm>
using namespace std;
template <class ... U>
void func(U... args) {
cout <<sizeof...(args) << endl;
}
void print() {
}
template<class T,class ...Args>
void print(T t, Args ...args) {
cout << t << endl;
print(args...);
}
template<int I = 0, class Tuple>
typename enable_if<I == tuple_size<Tuple>::value>::type printTp() {
}
template<int I = 0, class Tuple>
typename enable_if<I < tuple_size<Tuple>::value>::type printTp() {
printTp<I+1>();
}
template<class U>
void print(U u) {
cout << u << endl;
}
template<class ...Args>
void func1(Args ...arg) {
int arr[] = {(print(arg),0)...};
initializer_list<int> a{(print(arg),0)...};
}
template <class ...Args>
class Sum {
};
template <class First, class ...Rest>
class Sum<First, Rest ...> {
enum { value = Sum<First>::value + Sum<Rest...>::value};
};
template <class Last>
class Sum<Last> {
enum{ value = sizeof(Last)};
};
template<int ...>
class IndexSeq{};
template<int N, int ... Rest>
struct MakeIndex : MakeIndex<N - 1, N-1, Rest...> {
};
template<int ...Indexes>
struct MakeIndex<0, Indexes...> {
typedef IndexSeq<Indexes...> type;
};
void test_class_variable_template() {
using T = MakeIndex<3>::type;
cout << typeid(T).name() << endl;
}
template<int ...Indexes, class ... Args>
void helper_tuple(IndexSeq<Indexes...> index,tuple<Args...> tup) {
print(get<Indexes>(tup)...);
}
template <class ...Args>
void printArgs(Args ... args) {
helper_tuple(typename MakeIndex<sizeof...(Args)>::type(),make_tuple(args...));
}
int main() {
printArgs(1,3,4,5);
system("pause");
}
|