template function specialization query

A

Asfand Yar Qazi

Hi,

If I do this:

void
func(const int& i) {...}

template<class T>
func(const T& i) {...}

Is this equivalent to, or different to, the following?

template<class T>
func(const T& i) {...}

template<>
void
func<int>(const int& i) {...}
 
L

Leor Zolman

Hi,

If I do this:

void
func(const int& i) {...}

template<class T>
func(const T& i) {...}

Is this equivalent to, or different to, the following?

template<class T>
func(const T& i) {...}

template<>
void
func<int>(const int& i) {...}

Different, but you have to stress it to make the difference show up.
Consider this:

#include <iostream>
using namespace std;

void func1(const int& i) { cout << "func1(const int &)" << endl;}

template<class T>
void func1(const T& i) { cout << "func1(const T &) [template]" << endl;}

// Is this equivalent to, or different to, the following?

template<class T>
void func2(const T& i) { cout << "func2(const T &) [template]" << endl;}

template<>
void func2<int>(const int& i) { cout << "func2(const int&) [template]" <<
endl;}

int main()
{
cout << "Using ints:" << endl;
func1(5);
func2(5);

cout << endl;

cout << "Using longs:" << endl;
func1(5L);
func2(5L);
return 0;
}

Output:
Using ints:
func1(const int &)
func2(const int&) [template]

Using longs:
func1(const T &) [template]
func2(const T &) [template]

The difference is in the overload resolution rules. Using ints, the best
match is the completely-ordinary non-template.

Using longs, an exact match of a template specialization beats using a
non-template where a conversion has to happen.
-leor
 
A

Asfand Yar Qazi

Leor Zolman wrote:
The difference is in the overload resolution rules. Using ints, the best
match is the completely-ordinary non-template.

Using longs, an exact match of a template specialization beats using a
non-template where a conversion has to happen.
-leor

Ahhhh.....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,459
Latest member
Vida00R129

Latest Threads

Top