且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测可变参数模板中的第一个和最后一个参数?

更新时间:2023-09-01 18:51:04

如果这是您想要的,我并不肯定.但这里有两个名为 firstlast 的实用程序,它们分别采用可变参数模板和 typedef 第一个和最后一个类型:

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