变体模板,size_t

时间:2014-05-12 20:24:18

标签: c++ templates variadic-templates

我该如何解决这个问题?

#include <iostream>
using namespace std;

template<size_t I, size_t... T>
void fun()
{
    cout<<I<<endl;
    fun<T...>();
}

template<size_t I>
void fun()
{
    cout<<I<<endl;
}


int main()
{
    fun<1, 2>();
    fun<3>();
    return 0;
}

错误:

|21|error: call of overloaded 'fun()' is ambiguous| 
|21|note: candidates are:|
|5|note: void fun() [with unsigned int I = 3u;
unsigned int ...T = {}]| |12|note: void fun() [with unsigned int I =
3u]| In instantiation of 'void fun() [with unsigned int I = 2u;
unsigned int ...T = {}]':| |8|required from 'void fun() [with
unsigned int I = 1u; unsigned int ...T = {2u}]'| |20|required from
here| |8|error: no matching function for call to 'fun()'| |8|note:
candidate is:| |5|note: template<unsigned int I, unsigned int ...T>
void fun()| |5|note:   template argument deduction/substitution
failed:| |8|note:   couldn't deduce template parameter 'I'|

1 个答案:

答案 0 :(得分:4)

使可变参数版本仅接受两个或更多模板参数。

template<size_t I>
void fun()
{
    cout<<I<<endl;
}

template<size_t I1, size_t I2, size_t... T>
void fun()
{
    cout<<I1<<endl;
    fun<I2, T...>();
}