Reimundo Heluani - 1 year ago 51

C++ Question

I have two overloaded functions like

`void f(int);`

void f(std::string);

And two overloaded functions

`g`

`f`

`f`

`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`

`g`

`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`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**