How to detect the first and the last argument in the variadic templates?
For the 1st argument it is easy (just compare sizeof...(T)
with 0), but is there a way to detect the last element?
The example :
#include <iostream>
#include <typeinfo>
template < class... T >
struct A
{
int foo(int k){ return k; };
};
template < class T1, class... T >
struct A< T1, T... >
{
A() :a()
{
std::cout<<"A i="<<sizeof...(T)<<std::endl
<<" a type = " << typeid(T1).name()<<std::endl;
}
int foo(int k){ return anotherA.foo( a.foo(k) ); };
T1 a;
A< T... > anotherA;
};
struct B1
{
B1(){ std::cout<<"b1"<<std::endl; };
int foo(int k){ std::cout<<"b1::foo() k="<<k<<std::endl; return k+1; };
};
struct B2
{
B2(){ std::cout<<"b2"<<std::endl; };
int foo(int k){ std::cout<<"b2::foo() k="<<k<<std::endl; return k+2; };
};
struct B3
{
B3(){ std::cout<<"b3"<<std::endl; };
int foo(int k){ std::cout<<"b3::foo() k="<<k<<std::endl; return k+3; };
};
int main ()
{
A< B3, B2, B1 > a;
std::cout<<"the value is "
<<a.foo(5)
<< std::endl;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…