473,573 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloading vs. specialization of function templates


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 specialization? When
is specialization preferable to overloading? What is the intended
conceptual difference between the two? Any other guidance on other things I
need to know but don't know enough yet to even ask?

Thanks everyone - this group has been an invaluable resource to me and I
sure appreciate the time of those who have so generously assisted me!

Thanks,
Dave
#include <iostream>

using namespace std;

struct foo
{
int data;

bool operator<(const foo &rhs) const
{
return data < rhs.data;
}
};

template <typename T>
const T &my_max(cons t T &a, const T &b)
{
cout << "Point 1" << endl;
return (a < b) ? b : a;
}

template <>
const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 2" << endl;
return (a < b) ? b : a;
}

const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 3" << endl;
return (a < b) ? b : a;
}

int main()
{
foo a = {5};
foo b = {10};

// Yields "Point 3" as non-templates are
// preferred.
cout << my_max(a, b).data << endl;

return 0;
}
Jul 19 '05 #1
4 6459
Dave Theese wrote:
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 specialization? When
is specialization preferable to overloading? What is the intended
conceptual difference between the two? Any other guidance on other things I
need to know but don't know enough yet to even ask?
I had the same question sometime back and this is the reply from Bjarne
Stroustrup....

"For functions, you don't have to. Overloading will do. For classes, you don't
have an alternative. Note that when you specialize the specialzation doesn't
affect overload resolution rules, when you overload with a non-specialization,
overload resolution will prefer the non-specialization. "


Thanks everyone - this group has been an invaluable resource to me and I
sure appreciate the time of those who have so generously assisted me!

Thanks,
Dave

#include <iostream>

using namespace std;

struct foo
{
int data;

bool operator<(const foo &rhs) const
{
return data < rhs.data;
}
};

template <typename T>
const T &my_max(cons t T &a, const T &b)
{
cout << "Point 1" << endl;
return (a < b) ? b : a;
}

template <>
const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 2" << endl;
return (a < b) ? b : a;
}

const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 3" << endl;
return (a < b) ? b : a;
}

int main()
{
foo a = {5};
foo b = {10};

// Yields "Point 3" as non-templates are
// preferred.
cout << my_max(a, b).data << endl;

return 0;
}


Jul 19 '05 #2

Senthilvel Samatharman <Sa************ ********@adcc.a lcatel.be> wrote in
message news:3F******** *******@adcc.al catel.be...
Dave Theese wrote:
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 specialization? When is specialization preferable to overloading? What is the intended
conceptual difference between the two? Any other guidance on other things I need to know but don't know enough yet to even ask?
I had the same question sometime back and this is the reply from Bjarne
Stroustrup....

"For functions, you don't have to. Overloading will do. For classes, you

don't have an alternative. Note that when you specialize the specialzation doesn't affect overload resolution rules, when you overload with a non-specialization, overload resolution will prefer the non-specialization. "


Vandevoordes & Josuttis' recent book "C++ Templates"
imo covers this and other template issues quite well.

I must admit it will take me at least a few passes through this
great book to absorb everything therein. :-)

http://www.josuttis.com/tmplbook/index.html

-Mike

Jul 19 '05 #3

"Dave Theese" <ch**********@y ahoo.com> wrote in message
news:KUa7b.1466 5$QT5.9944@fed1 read02...

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 specialization? When is specialization preferable to overloading? What is the intended
conceptual difference between the two? Any other guidance on other things I need to know but don't know enough yet to even ask?

Thanks everyone - this group has been an invaluable resource to me and I
sure appreciate the time of those who have so generously assisted me!

Thanks,
Dave
#include <iostream>

using namespace std;

struct foo
{
int data;

bool operator<(const foo &rhs) const
{
return data < rhs.data;
}
};

template <typename T>
const T &my_max(cons t T &a, const T &b)
{
cout << "Point 1" << endl;
return (a < b) ? b : a;
}

template <>
const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 2" << endl;
return (a < b) ? b : a;
}

const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 3" << endl;
return (a < b) ? b : a;
}

int main()
{
foo a = {5};
foo b = {10};

// Yields "Point 3" as non-templates are
// preferred.
cout << my_max(a, b).data << endl;

return 0;
}

I am not so clear about your question but here goes. I am using simple
examples
to explain the concepts.

Use composition ( has-a relationship,em bedded objects ) over inheritance
(i.e specialisation of a base class).
If there are many related classes differing in the parameters only by the
type, then use templates.
Use operator or function overloading as a last resort.
As an example the sign plus can mean binary addition eg 4 + 7 or string
concatenation or adding
two graphic figures together depending on your program or class.
Thus in this case the plus sign token is an overloaded operator.

As an example for function overloading, lets say for a function
AverageOf3Numbe rs(param1, param2, param3 ,...)
where average can mean mean or median.
The AverageOf3Numbe rs( totalof3Numbers ) function divides the param1 by 3 to
get the average, as in mean case;
in the other case,the median interpretation of average, all 3 numbers are
passed into the function as in,
AverageOf3Numbe rs(3 , 5, 8) function does a integer comparison and gives 5
as the median(average) .

That is in your class definition, there are two AverageOf3Numbe rs( ) methods
declared.

However, if you just want to have one interpreation of the meaning of
average , as mean, but the types of the parameters differ,
use a template.
AverageOf3Numbe rs(integer1, integer2, integer3) ; AverageOf3Numbe rs(float1,
float2, float3) etc
Use a template class.
As an example of operator-loading, You can write your own complex nos. class
to add , subtract, divide and multiply
complex nos. In this class, all "+", "-", "*" and "/" will be overloaded ,
the methods will be written by you.

First check with a C++ standard book and a STL library book before writing
your own classes. The STL is template-based
and already has many useful methods , functions,funct ors you can use etc

Regards,
Govin

Jul 19 '05 #4
On Mon, 8 Sep 2003 19:30:51 -0700, "Dave Theese"
<ch**********@y ahoo.com> wrote:

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
specializati on and an overload. Note that the overload is identical to the
specializati on 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 specialization?
Non-template overloads can be useful if you want the function to be
chosen in the face of conversions and non-exact parameter matches.

Also, because partial specialization doesn't exist for function
templates, you have to use overloading when you need a special
implementation for a subset of cases of a template.

Whenis specialization preferable to overloading?
When you just want to provide a special implementation for a
particular type, but don't want to effect overload resolution.

What is the intendedconceptual difference between the two?
An overload adds a new function, a specialization just specializes an
implementation of a function you already have.

Any other guidance on other things Ineed to know but don't know enough yet to even ask?


There's a bit more information here:
http://www.gotw.ca/gotw/049.htm

and a ludicrous amount of information about all sorts of C++ things
here:
http://www.gotw.ca/gotw/

Tom
Jul 19 '05 #5

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

Similar topics

5
6574
by: Levent | last post by:
Hi, Why doesn't this work? (tried with gcc 3.3.3 and VC++ 7.1): #include <iostream> template<class T, unsigned N> struct Foo { void func(); }; template<class T, unsigned N>
3
2446
by: Starx | last post by:
I was wondering if someone could help me get around this problem I'm having. I'm writing a fraction class and would like to overload the binary arithmetic operators so that when any numerical data type (int, double, long double, etc.) is used with a fraction it is first converted to a fraction and then added, the result being a fraction. ...
16
16235
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 ]
7
2084
by: Kai-Uwe Bux | last post by:
Hi folks, I observed something that puzzles me. When I do namespace xxx { using std::swap; } it appears that xxx::swap and std::swap are not strictly equivalent. In particular, I think that my implementation will only choose the partial specialization for std::vector when std::swap is used.
6
5003
by: flopbucket | last post by:
Could someone explain to me what the difference is between function template specialization and function overloading? I guess overloading can change the number of parameters, but otherwise they seem very similar to me - i.e. they both provide specialized functions for depending on the parameter types. Thanks
1
2496
by: nyl2002 | last post by:
I have written the following very short template class in testclass.h: template<typename C,typename T> class TestClass { public: TestClass() {}; ~TestClass(); private: T testFunction(T dummy); };
11
3798
by: jakester | last post by:
I am using Visual C++ 2007 to build the code below. I keep getting linkage error. Could someone please tell me what I am doing wrong? The code works until I start using namespace for my objects. Error 1 error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char & __cdecl graph::operator<<(class...
8
1940
by: mattias.nissler | last post by:
Hi! Here is a problem I ran into at work. The following example doesn't compile on gcc-4.1: struct cons_end {}; template<typename U,typename Vstruct cons { U elem; V tail;
13
6564
by: mike b | last post by:
Hello everyone, thanks in advance for your help. I'm new to C++ templates and have run into some issues using member function templates. I have a shared library containing templates that I'm trying to use from an executable, compile using gcc 4.1.2. Everything works fine until I try specializing one of the static member function templates...
0
7760
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...
0
7679
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7996
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. ...
0
8191
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8049
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...
0
6392
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5573
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
1
1289
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1029
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...

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.