I have a human class with ctor using universal reference
class Human {
public:
template<typename T>
explicit Human(T&& rhs) {
// do some initialization work
}
Human(const Human& rhs); // the default ctor I don't care about
}
Now if I have a const Human object
const Human one_I_do_not_care; // then play with that
Human the_human_I_care(one_I_do_not_care) // now create another one
Does the last line use the template ctor or the default ctor? My understanding is the "const" will disqualify the template ctor, am I correct?
Human the_human_I_care(one_I_do_not_care) // line in question
By const disqualify the template ctor, I mean adding const then it would not match the template ctor, not it still matches two but compiler picks one.
Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .
It cannot hurt to declare it const if you know that your function needs not modify its value during execution. Note that functions that change their arguments, when arguments are passed by value, should be rare. Declaring your variable const can prevent you from writing if (aIn = someValue) . Save this answer.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
Universal reference was a term Scott Meyers coined to describe the concept of taking an rvalue reference to a cv-unqualified template parameter, which can then be deduced as either a value or an lvalue reference.
Does the last line use the template ctor or the default ctor? My understanding is the
const
will disqualify the template ctor, am I correct?
No. You are passing a const
-qualified Human
as an argument. Since both constructors would match equally well (i.e.: if the template would be instantiated to take a const Human&
), then the non-template constructor is preferred over the template (and no template instantiation for a const Human&
parameter ever occur).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With