Connecting Tech Pros Worldwide Help | Site Map

Function template specialization

 
LinkBack Thread Tools Search this Thread
  #1  
Old January 17th, 2008, 10:05 AM
C++Liliput
Guest
 
Posts: n/a
Default Function template specialization

I have a template function of the type

template<typename T>
const T max(const T& a, const T& b)
{
return a b ? a : b;
}

I provide a template specialization only for C strings as follows:

template<>
const char* max(const char*& a, const char*& b)
{ -------------------------------------------------------------------------------------------------
Quote:
ERROR
return strcmp(a, b) 0 ? a : b;
}

Now I have the following code in main:

const char* cstr1 = "STRING";
const char* cstr2 = "string";

const char* cstrMax = ::max(cstr1, cstr2);

when I compile this code on my Solaris machine, I keep getting the
error "Could not find a match for max<T>(const char*&, const char*&)"
at the line mentioned above (dotted line ending with ERROR).

Surprisingly when I change my template definition to the following,
everything compiles fine:

template<typename T>
T max(T& a, T& b)
{
return a b ? a : b;
}

As you can see all I have done is remove the const keyword qualifying
the arguments and the return type. In the first case, I would assume
that the typename should evaluate to "char*" but that obviously does
not happen. In the second case, the typename obviously evaluates to
"const char*" and everything works fine. What is the reason that there
is a compilation error in the first case?

  #2  
Old January 17th, 2008, 10:15 AM
Michael DOUBEZ
Guest
 
Posts: n/a
Default Re: Function template specialization

C++Liliput a écrit :
Quote:
I have a template function of the type
>
template<typename T>
const T max(const T& a, const T& b)
{
return a b ? a : b;
}
>
I provide a template specialization only for C strings as follows:
>
template<>
const char* max(const char*& a, const char*& b)
{ -------------------------------------------------------------------------------------------------
Quote:
>ERROR
return strcmp(a, b) 0 ? a : b;
}
Specialization of T=char* is
template<>
char* const max(char* const& a, char* const& b)
{
....
}

You should define
char const * const max(char const * const& a, char const * const& b)
{
....
}


 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,989 network members.