Reimundo Heluani Reimundo Heluani - 1 month ago 5
C++ Question

c++ overloaded functions with equal implementation

I have two overloaded functions like

void f(int);
void f(std::string);


And two overloaded functions
g
with the same prototypes as
f
, but which are simple wrappers to
f
, hence their implementations are exactly the same:

void g(int n) { f(n);}
void g(std::string n) { f(n); }


Is there a way of avoiding writing twice the implementation of
g
? I know this can be done by declaring
g
via a template like

template<typename T> g(T n) { f(n);}


but then I'll have to type the type in the function call like in

g<int>(2);
g<std::string>("42");


I wander what's the correct way of avoiding writing twice the implementation of
g
without forcing the user to explicitly write the typename in each function call?

Answer

“but then I'll have to type the type in the function”, no, you don't have to. Template argument deduction does that for you. So, a function template is a practical solution.

The one you've written,

template<typename T> g(T n) { f(n);}

is fine except that it needs a void return type.


You can support move-optimizations as follows:

template< class Arg >
void g( Arg&& arg ) { f( std::forward<Arg>( arg ) ); }

Here the && does not denote an rvalue reference but a so called universal reference, because it's applied to a template argument that can already be a reference.

The effect of that is that std::forward in most cases can reproduce exactly the kind of the actual argument, which is called perfect forwarding.