So I have this piece of code and out of convenience I want the default parameter for its constructor be of the int kind and 0. (I have more parameters in a class of my project and one of them is optional and I don't want to write the constructor twice because its big)
class mama{
public:
template<typename x> mama(x i=int(0)){}
};
int main(){
mama x;
}
This doesn't work because it says it can't find the constructor so is there another way I can do this?
error: no matching function for call to ‘mama::mama()'
note: candidates are: mama::mama(const mama&)
Refactor your constructor into a private initialization function and wrapper constructors, then add a default, like so:
class mama {
private:
template<typename x> void init(x i) { /* ... */ }
public:
template<typename x> mama(x i) { init(i); }
mama() { init((int)0); }
};
Note that default template parameters are not allowed for function templates. Why not create a class template?
template <class T=int>
class mama{
public:
mama<T>(T i=0){}
};
int main(){
mama<> x; // no argument based template parameter deduction possible
}
Default value works just like overload, so...
class mama{
public:
template<typename x> mama(x i){}
mama(int i = 0) {}
};
When you create mama with no argument, the construct with default int is matched before any templated constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.