+ 1

Need of universal reference

Hi When we declare a method which has T&& as argument where T is template type , it is called universal reference. With Universal reference, one can pass l value and r value as argument to a method. But it always looses r value reference and considered as l value reference for sub sequent call. This can be avoided by perfect forward. However, it is not at all necessary if we directly have two methods one for lvalue and one for r value reference. Question is that why to use universal reference and then keep in mind about perfect forwarding? Can we directly not have two different methods each for r and l value reference? Is there any benefit or use case of universal reference?

23rd Oct 2021, 6:49 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Réponse
+ 2
As far as I know, universal reference was introduced to solve an issue that arises with taking a reference to an l-value reference. Consider the following snippet of code where our class has two different methods each for r and l value reference template <class T> class Foo { void test(T& param) { T& ref=param; } void test(T&& param) { T& ref=param; } } Everything works fine, until the type T itself becomes a reference type (for example int&). Then some problems arise no? So maybe to solve this, the universal reference was introduced. Maybe refer the following https://drewcampbell92.medium.com/understanding-move-semantics-and-perfect-forwarding-part-3-65575d523ff8 https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers Excuse me if anything is wrong, I'm only an intermediate C++ learner =)
24th Oct 2021, 2:11 AM
Rishi
Rishi - avatar