Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does 'const' disqualify universal reference?

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.

like image 960
WhatABeautifulWorld Avatar asked Jan 20 '18 17:01

WhatABeautifulWorld


People also ask

Does const reference copy?

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 .

Can we declare a non reference function argument const?

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.

Can const reference be modified?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.

What is a universal reference?

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.


1 Answers

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).

like image 176
ネロク・ゴ Avatar answered Sep 22 '22 05:09

ネロク・ゴ