c++14 逆序/反转 tuple

编译: g++ tuple.cpp -std=c++14
c++14支持函数返回auto的返回类型,c++11需要返回类型后置。
由于 get<N>(tuple)中的N必须是常量,用普通的循环遍历不了,tuple的特性很多是在编译期
完成的。

#include <iostream>
#include <tuple>

using namespace std;

template<typename T, size_t N>
struct RTuple
{
    static auto reverse(T& tup)
    {
        return move( tuple_cat( make_tuple(get<N-1>(tup)), RTuple<T,N-1>::reverse(tup)) );
    }
};

template<typename T >
struct RTuple<T, 1>
{
    static auto reverse(T& tup)
    {
        return move( make_tuple(get<0>(tup)) );
    }
};

template<typename T>
struct RTuple<T,0>
{
    static auto reverse(T& tup)
    {
        return move(tup);
    }
};

int main(int argc, char* argv[])
{
    auto t1 = make_tuple(1,2,3,4);
    auto in1 = RTuple<decltype(t1),4>::reverse(t1);
    cout<<get<0>(t1)<<",";
    cout<<get<1>(t1)<<",";
    cout<<get<2>(t1)<<",";
    cout<<get<3>(t1)<<endl;
    cout<<get<0>(in1)<<",";
    cout<<get<1>(in1)<<",";
    cout<<get<2>(in1)<<",";
    cout<<get<3>(in1)<<endl;

    tuple<> t2;
    auto size = tuple_size<decltype(t2)>::value;
    cout<<size<<endl;
    //if ( size > 0 )
    //    cout<<get<0>(t2)<<endl;

    auto in2 = RTuple<decltype(t2),0>::reverse(t2);
    size = tuple_size<decltype(in2)>::value;
    cout<<size<<endl;
    //if ( size > 0 )
    //    cout<<get<0>(in2)<<endl;
    return 0;
}
上一篇:关于python列表和元组的基本操作


下一篇:PostgreSQL统计信息的几个重要视图