Question

How can I solve this problem?

#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;
}

errors:

|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'|
Was it helpful?

Solution

Make the variadic version only accept two or more template arguments.

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...>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top