Why universal reference is not moving + template specialization | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why universal reference is not moving + template specialization

Refer class below: I have two constructors one for const l value ref of string and one for rvalue ref It works fine but when i use universal reference with forward, it does not move Whats missing here ? I just want to move rvalue ref with just one constructor Once this issue is resolved, how to use template specialization ? I just want universal reference work for string and other types should not be compiled. In other words, it should work for string only https://code.sololearn.com/cmZg02R12wSs/?ref=app

11th Dec 2022, 5:52 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 1
Ketan Lalcheta you are getting different results because you haven't initialised "m_str" anywhere when an l-value is passed to constructor and "myString(const string& str)" is called. universal reference is working correctly as "s" is an l-value and hence the constructor accepting universal argument forwards an l-value reference while initialising "m_str" ( the second allocation is when contents of "str" are "copied" to "m_str" which never happens in the case of two constructors where one of the constructor you created never initialised "m_str")
14th Dec 2022, 4:33 PM
Arsenic
Arsenic - avatar
+ 1
You are missing actual assignment to *m_str* when calling constructor accepting const l-value references "myString(const string& str)". The constructor with universal argument is working correctly for all the provided cases. As for restricting universal argument to one type ( string in your case ), you can achieve that with default template parameters trickery https://code.sololearn.com/ctIj5gWeD79N/?ref=app P.S. I am pretty sure you can also achive this much easily with C++20 "concepts" but sololearn's code playground currently doesn't enable it while compiling.
14th Dec 2022, 12:29 PM
Arsenic
Arsenic - avatar
0
If universal argument is working correctly , then why I am getting different results for case below: { string s = "Ketan12345678970"; myString obj(s); } Does code output remain same when 1. Two constructor are provided 2. Or only one universal ref constructor is provided
14th Dec 2022, 2:43 PM
Ketan Lalcheta
Ketan Lalcheta - avatar