特定类型列表的函数重载

时间:2012-05-11 04:47:34

标签: c++ templates c++11 overloading

我正在尝试为类型列表编写一些适配器代码。以下是用于此目的的实验代码:

struct null
{
};

template<typename first, typename second>
struct cell
{
    typedef first head;
    typedef second tail;
};

template <
    typename T1 = null, typename T2 = null, typename T3 = null,
    typename T4 = null, typename T5 = null, typename T6 = null,
    typename T7 = null, typename T8 = null, typename T9 = null,
    typename T10 = null, typename T11 = null, typename T12 = null,
    typename T13 = null, typename T14 = null, typename T15 = null,
    typename T16 = null, typename T17 = null, typename T18 = null
>
struct type_list
{
private:
    typedef typename type_list <
        T2, T3, T4, T5, T6, T7, T8, T9, T10,
        T11, T12, T13, T14, T15, T16, T17, T18
    >::type tail;

public:
    typedef cell<T1, tail> type;
};

template<>
struct type_list<>
{
    typedef null type;
};

template<typename T>
void test(T);

#include <cstdio>

template<typename T1, typename T2>
void test(typename type_list<T1, T2>::type)
{
    // won't be instantiated
    printf("type_list<T1, T2>::type\n");
}

template<typename T1, typename T2>
void test(cell<T1, cell<T2, null>>)
{
    printf("cell<T1, cell<T2, null>>\n");
}

int main()
{
    // Below causes compile error when 'void test(cell<T1, cell<T2, null>>)' is absence
    test(type_list<int, int>::type());
}

输出:

cell<T1, cell<T2, null>>

我想使用void test(type_list<T1, T2>::type)而不是void test(cell<T1, cell<T2, null>>),因为前者更简洁一些。我的问题是

  • 我不能使用前者的具体原因是什么?
  • 有没有解决方法? (直接使用cell除外:()

当然,type_list只是类型列表生成的包装器,所以'::type'之后只能删除type_list<blah>

谢谢。

1 个答案:

答案 0 :(得分:0)

存在:

template<typename T>
void test(T);

使它成为函数调用的最佳匹配(直到你放入单元格重载)。尝试将您的函数调用更改为:

test<int,int>(type_list<int, int>::type());