所以我有这段代码,为了方便起见,我希望它的构造函数的默认参数是 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/