简体   繁体   中英

Program fails to call the specialized template implementation

I am trying to learn C++ template. While I run the following example, the program couldn't call the specialized template implementation. Therefore, I got the wrong output. Could anybody tell why?

template <class T>
T max(T a, T b)
{
    cout << "2 ..." <<endl;
    return a > b ? a : b;
}
template<>
char* max(char* a, char* b)
{
    cout << "1 ..." <<endl;
    return strcmp(a, b) > 0 ? a : b;
}
int main()
{
    cout << max("Aladdin", "Jasmine") << endl;
    return 0;
}

The arguments are passed as constant char. Therefore, try the following code instead. Note that I also included the necessary header file includes. Moreover, it is highly advisable to use std::cout , or use using std::cout; .

#include <iostream> 
#include <cstring> 

template <class T> 
T max(T a, T b) 
{ 
    std::cout << "2 ..." << std::endl; 
    return a > b ? a : b; 
} 

template<> 
const char* max(const char* a, const char* b) 
{ 
    std::cout << "1 ..." << std::endl; 
    return std::strcmp(a, b) > 0 ? a : b; 
} 

int main() 
{ 
    std::cout << max("Aladdin", "Jasmine") << std::endl; 
    return 0; 
}

The reason you're seeing the issue is that the arguments you're passing are of type char const * (also can be spelled const char * ). There isn't any standard way that I know of in C++ to print out the full name of a type. But there is a way to test this sort of thing..

One of the problems of templates is that the system will expand any templates it can. And so you will have code mysteriously work a certain way and not be completely sure why. One way you could've gotten the compiler to tell you exactly what the problem was in this case was to try to remove the template:

#include <iostream>
#include <cstring>

using ::std::cout;
using ::std::strcmp;

char* max(char* a, char* b)
{
    cout << "1 ..." << '\n'; // Don't use ::std::endl Use cerr if you need flushing.
    return strcmp(a, b) > 0 ? a : b;
}
int main()
{
    cout << max("Aladdin", "Jasmine") << '\n';
    return 0;
}

The compiler would've helpfully told you that you were trying to call a function that took non-const arguments with const arguments, and you would've learned exactly what the problem was.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM