473,725 Members | 2,251 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Templates vs overloaded functions?

If a function should work with different types you normally overload it:

void myfun(int a){
// do int stuff
}

void myfun(std::stri ng str){
// do string stuff
}

void myfun(double d){
// do double stuff
}

But you can also use a specialized template function instead:

template<typena me T>
void mytemp(T) {
// "default case" if no other match
}

template<>
void mytemp(int a) {
// in case of int
}

template<>
void mytemp(std::str ing str) {
// in case of string
}
template<>
void mytemp(double d) {
// in case of double
}
The only difference I have found is the correct template is only used if
the arguments match exactly:

http://www.parashift.com/c++-faq-lit...html#faq-35.11

But is that the only difference? Are the types decided at compile time
in both examples etc?
May 11 '07 #1
2 3884
desktop wrote:
If a function should work with different types you normally overload
it:
void myfun(int a){
// do int stuff
}

void myfun(std::stri ng str){
// do string stuff
}

void myfun(double d){
// do double stuff
}

But you can also use a specialized template function instead:

template<typena me T>
void mytemp(T) {
// "default case" if no other match
}

template<>
void mytemp(int a) {
// in case of int
}

template<>
void mytemp(std::str ing str) {
// in case of string
}
template<>
void mytemp(double d) {
// in case of double
}
The only difference I have found is the correct template is only used
if the arguments match exactly:

http://www.parashift.com/c++-faq-lit...html#faq-35.11

But is that the only difference? Are the types decided at compile time
in both examples etc?
No. If your code never makes use of 'mytemp(int)' or 'mytemp(double) ',
the code for them will never be generated. I heard a rumour that today
linkers can detect that a [regular] function is not used and throw its
code out, but I would have to see it to believe.

Yes, involvement of conversions is the main reason to prefer regular
[overloaded] functions over template specialisations . If you happen
to use mytemp(blah), and 'blah' is 'short', an overloaded function
'mytemp(int)' will be used, whereas 'mytemp<int>(in t)' will never be
picked (and the default case will be then used). Same if 'blah' is
'float' -- the 'mytemp<double> ' specialisation isn't applicable.

Also, your example contains 3 overloaded functions and 4 functions
based on the template (one generic and three specialised). They are
not exactly equivalent.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 11 '07 #2
On May 11, 7:39 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
desktop wrote:
But is that the only difference? Are the types decided at compile time
in both examples etc?
No. If your code never makes use of 'mytemp(int)' or 'mytemp(double) ',
the code for them will never be generated. I heard a rumour that today
linkers can detect that a [regular] function is not used and throw its
code out, but I would have to see it to believe.
Put them in a separate compilation unit, put the results in a
library, and I don't know of a linker which won't incorporate
just the functions it needs. VC++ has an option to support this
even if the functions aren't in separate compilation units, but
I'm not sure whether it is such a good idea.
Yes, involvement of conversions is the main reason to prefer regular
[overloaded] functions over template specialisations . If you happen
to use mytemp(blah), and 'blah' is 'short', an overloaded function
'mytemp(int)' will be used, whereas 'mytemp<int>(in t)' will never be
picked (and the default case will be then used). Same if 'blah' is
'float' -- the 'mytemp<double> ' specialisation isn't applicable.
Also, your example contains 3 overloaded functions and 4 functions
based on the template (one generic and three specialised). They are
not exactly equivalent.
That's the big difference, of course. If you have a template,
the compiler will do type deduction on it. If it succeeds, the
results will be added to the overload set. If it fails, they
won't be.

In his first example, the results would have been more or less
the same if he had provided overloaded functions, rather than
template specializations . The template function declaration
would be instantiated, but any time it corresponded to an
overloaded non-template function, that function would be chosen
instead.

There is one big difference, however: you can force the function
you want using templates, by explicitly specifying the template
arguments, e.g.:

mytemp< int >( someDouble ) ;

Of course, explicitly casting the argument to the targeted type
has almost the same results: the only difference is if the
conversion uses an explicit constructor, in which case casting
the argument works, but the above would fail.

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 11 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6479
by: Dave Theese | last post by:
Hello all, I'm trying to get a grasp of the difference between specializing a function template and overloading it. The example below has a primary template, a specialization and an overload. Note that the overload is identical to the specialization except, of course, for the missing "template <>". I don't know if my questions will be a bit too broad or not, but I thought I'd give it shot... When is overloading preferable to...
16
16282
by: WittyGuy | last post by:
Hi, What is the major difference between function overloading and function templates? Thanks! http://www.gotw.ca/resources/clcm.htm for info about ]
44
2409
by: bahadir.balban | last post by:
Hi, What's the best way to implement an overloaded function in C? For instance if you want to have generic print function for various structures, my implementation would be with a case statement: void print_structs(void * struct_argument, enum struct_type stype) { switch(stype) { case STRUCT_TYPE_1:
4
1496
by: qning88 | last post by:
I would like to find out how I can effectively make use of templates in theexample below. In Class A, I have 3 overloaded member functions "send" for handling the different messages. Although the messages are different, the way to handle the message is the same. Hence I'm thinking of using templates to reduce the number of lines in the code. ------ ClassA.h ------ struct Message1;
25
3327
by: Ted | last post by:
I'm putting the posts that follow here (hopefully they will follow here!) because they were rejected in comp.lang.c++.moderated. It behooves anyone reading them to first read the the thread of the same subject in clc++m to get the more of the context. Ted
4
1538
by: Dilip | last post by:
How did the Koenig lookup come to be associated with templates? If I have something like this: (no template code) namespace X { enum E { e1 }; void f(E) { } }
104
4583
by: JohnQ | last post by:
Well apparently not since one can step thru template code with a debugger. But if I was willing to make the concession on debugging, templates would be strictly a precompiler thing? I have a feeling the answer I'm going to get back will be "no, because templates have taken on a life of their own since their original conception and now also affect compiler implementation" (read: not good, IMO. John
6
1453
by: pleexed | last post by:
hello, this is my first post in a newsgroup, i hope i do everything right :) first of all, i am sure there have been a lot of "are templates slow?" questions around, but i think what i would like to know is not that general. furthermore, what i ask here may have hardly any impact on the generated code size or performance; i am not trying to micro- optimize anything, i am just curious how templates are compiled by modern compilers of...
0
1470
by: WebCM | last post by:
I hope you can spend some time and help me to select proper application design and programming issues. :) I'm making new version of CMS. I've been mostly theorizing about it for a recent months. Main Goals The main goal of this CMS is speed and performance. It should work fast on slower or overloaded servers. Other goals are: easy appearance editing, low size, care about input data (e.g. if error occurs, form is sent to client with his...
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.