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

标签 c++ arguments c++11 variadic-templates

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

对于第一个参数很容易(只需将 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;
}

最佳答案

如果这是你想要的,我不肯定。但这里有两个名为 firstlast 的实用程序,它们分别采用可变参数模板和 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/

相关文章:

c++ - 从初始化列表中提取模板类型

c++ - cpp make_shared 用于空指针

c++ - 我在 VS2015 中处理代码时得到不同的输出。有什么解释吗?

linux - 从我的 bash 脚本调用另一个 bash 脚本,给它一些输入值

c++ - 通过引用使用 vector<int>::iterator 但有错误

c++ - C++ 中的内存模型 : sequential consistency and atomicity

C++ 嵌入式系统摩尔斯电码

perl - 我应该如何将对象传递给子程序?

email - 向电子邮件中的本地文件的 HTML 链接添加参数

c++ - "modifier is not allowed on a destructor"在VS2013中用nvcc编译时出错