Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

c++ - How to detect the first and the last argument in the variadic templates?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not positive if this is what you want. But here are two utilities named first and last that take variadic templates and typedef the first and last type respectively:

#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() << '
';
    std::cout << typeid(T::last).name() << '
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...