可变模板,size_t

Variadic templates, size_t

本文关键字:size      更新时间:2023-10-16

如何解决这个问题?

#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'|

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

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...>();
}