gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:14:25 24 4
gpt4 key购买 nike

我有一个模板化类,但遇到了一些问题。我在另一个类上有这个指令:

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

关于c++ - 将模板函数与默认参数混合时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18948155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com