如何检测可变参数模板中的第一个和最后一个参数?
对于第一个参数很容易(只需将 sizeof...(T)
与 0 进行比较),但是有没有办法检测最后一个元素?
例子:
#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;
}
最佳答案
如果这是你想要的,我不肯定。但这里有两个名为 first
和 last
的实用程序,它们分别采用可变参数模板和 typedef 第一个和最后一个类型:
#include <iostream>
#include <typeinfo>
template <class T1, class ...T>
struct first
{
typedef T1 type;
};
template <class T1, class ...T>
struct last
{
typedef typename last<T...>::type type;
};
template <class T1>
struct last<T1>
{
typedef T1 type;
};
template <class ...T>
struct A
{
typedef typename first<T...>::type first;
typedef typename last<T...>::type last;
};
struct B1 {};
struct B2 {};
struct B3 {};
int main()
{
typedef A<B1, B2, B3> T;
std::cout << typeid(T::first).name() << '\n';
std::cout << typeid(T::last).name() << '\n';
}
关于c++ - 如何检测可变参数模板中的第一个和最后一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7661643/