将模板函数与默认参数混合时出错

Error in mixing template function with default argument

本文关键字:参数 混合 出错 默认 函数      更新时间:2023-10-16

我有一个模板化类,我遇到了一些问题。我在另一个类中有这种入侵:

value.push_back(x);

作为 x unsigned int,值称为 List<unsigned int> 的模板化类,并push_back此函数:

template <class T>
void List<T>::push_back(T a=T(),int l=1){
    (*this).resize((*this).size+l,a);
}

我在代码块中有以下错误:

...mp.h|86|error: no matching function for call to 'List<unsigned int>::push_back(unsigned int)'
...mp.h|86|note: candidate is:
...list.h|36|note: void List<T>::push_back(T, int) [with T = unsigned int]
...list.h|36|note:   candidate expects 2 arguments, 1 provided

我不知道该怎么做,该函数已经有 int 的默认值,并且我已经尝试了 2 个不同的编译器,我真的不想在push_back中添加另一个参数以使其变得push_back(x,1).

是否在声明中包含默认值?

template <class T>
struct List 
{
    void push_back(T a=T(),int l=1);
};

一个好的编译器应该拒绝编译它,如果你没有(或者至少警告过这种差异),但是,只是为了确定。

习惯上"只是"在类中实现模板成员:

template <class T>
struct List 
{
    void push_back(T a=T(),int l=1)
    {
        (*this).resize((*this).size+l,a);
    }
};