More C++ Idioms/Return Type Resolver

= Return Type Resolver =

Intent
Deduce the type of the variable being initialized or assigned to.

Motivation
The type of the variable being initialized can be a useful information to have in certain contexts. Consider, for instance, we want to initialize STL containers with random numbers. However, we don't know the exact type of the container expected by the user. It could be std::list, std::vector or something custom that behaves like STL container. A straight-forward approach to write and use such a function would be as follows.

Note that the type of the container must be passed to the function because that is the desired return type of the function. Clearly, the type must be repeated at-least twice. Return type resolver idiom can be used to address this issue.

Solution and Sample Code
Return type resolver idiom makes use of a proxy class and templatized conversion operator functions in the class. getRandomN function above can be implemented with a class and a member conversion function as follows.

getRandomN class has a constructor and a templatized conversion operator function. For initialization, a temporary object of getRandomN class is created and assigned to the desired container class. C++ compiler attempts to convert the temporary object into the container class object. The only way to do that is via the conversion operator. The conversion operator is instantiated with the type of the container that is being populated. Due to automatic resolution of the return type, the user does not have to spell it out again. Note that  member function has been used instead of   because   does not support.

Known Uses
The nullptr idiom makes use of the return type resolver idiom to automatically deduce a null pointer of the correct type depending upon the pointer variable it is assigning to.

Related Idioms

 * nullptr