简体   繁体   中英

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?

“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 .

Is there a way of avoiding writing twice the implementation of g?

Yes, there is.

I know this can be done by declaring g via a template like

There you go.

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

No, you don't. You can let the compiler to deduce the types:

g(2);
g("42");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM