How to avoid overload, templates ? How to work with it

I have a simple function that can receive any kind of numeric value.

My_function (int value) {}
My_function (double value) {}
....
How can I change this by using templates ?
I dont want to use myfunction<int>(value), I'd prefer to find out the var type inside my function, so I can call the function without be in mind the type of var that I pass to.
I do this in old VB using variant type.But ... in c`++?
Any help ?
Thanks
If you have the template parameter as argument type in the function, you don't have to explicitly call it as a template
eg:
1
2
3
4
5
6
7
template < class T >
    void My_function ( T value ) // T used as type for a function parameter
{}

//...

My_function ( 5 ); // since 5 is an int is the same as calling My_function<int> ( 5 ) 
Ok.
By last, I have seen that this kind of functions are 'created' on the fly ? So it is recommended to use only with functions not linked with the main performance ?
Actually, it is recommended not to use templates at all unless you got a good reason to do so. Being to lazy to overload functions is NOT a good reason.
tonnot wrote:
By last, I have seen that this kind of functions are 'created' on the fly ?

Templates resolve to regular functions or classes with the used types at compile time. Nothing is created on the fly.

@hanst99: why is it not recommended?
Bump. I'd still like to know.
Why? Because it's a waste to use templates for functions that do not behave like templates. But maybe that's just my personal preference kicking in here. I like to differ between cases where you use different but similar objects with the same interface, and truly generic problems. Maybe that's just me, but I just don't like to see people using templates as typesafe macros. Though I gotta admit that "it is not recommended" was a poor choice of words on my part.
I see, thanks.
So it is recommended to use only with functions not linked with the main performance ?
It's not really a matter of performance. It may be legitimate to want a template function that handles numeric types. That, to my mind, this isn't an abuse of templates.

There is at least one technical hitch to work around if you wanted to put this code in a library that all sorts of users might see, and that is restricting it to numeric types only. There's a clear solution to that in Loki. If it's your own program and you have complete control on how the function's called, you don't need to get into all that.
Because the OP said "I'd prefer to find out the var type inside my function", I think an overload would be best. I think templates are best used as a duck typing mechanism.
Topic archived. No new replies allowed.