How can I write a template function that returns either a reference or a value?

  • A+
Category:Languages

I'd like to write a template function that returns either a reference or a value depending on some compile time expression. What I've tried so far is something like this:

template<typename T> auto&& Func() {   if constexpr (some_compile_time_expression)   {     return GetReferenceFromSomewhere();   }   else   {     return GetValueFromSomewhere();   } } 

This works fine for all types of references but doesn't work for values. For example, if GetValueFromSomewhere returns a Foo, then the compiler deduces the return type of Func as Foo&& and warns that I'm returning the address of a temporary.

Is there any way to make this work, or am I forced to tease the two branches apart somehow (through function overloads or some such)?

 


Use decltype(auto) for the return type placeholder, it will preserve the exact value category of the function you're calling in the return statement

template<typename T> decltype(auto) Func() {   if constexpr (some_compile_time_expression_dependent_on_T)   {     return GetReferenceFromSomewhere();   }   else   {     return GetValueFromSomewhere();   } } 

Live demo

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: