gpt4 book ai didi

c++ - 构造函数中的默认模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:49:43 25 4
gpt4 key购买 nike

所以我有这段代码,为了方便起见,我希望它的构造函数的默认参数是 int 类型和 0。(我的项目的一个类中有更多参数,其中一个是可选的,我不'想写两次构造函数,因为它很大)

class mama{
public:
template<typename x> mama(x i=int(0)){}
};

int main(){
mama x;
}

这行不通,因为它说找不到构造函数,所以有没有其他方法可以做到这一点?

error: no matching function for call to ‘mama::mama()'
note: candidates are: mama::mama(const mama&)

最佳答案

请注意,函数模板不允许使用默认模板参数。为什么不创建一个类模板?

template <class T=int>
class mama{
public:
mama<T>(T i=0){}
};

int main(){
mama<> x; // no argument based template parameter deduction possible
}

关于c++ - 构造函数中的默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831952/

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