C++에서 template을 사용하더라도 특정 함수를 부르게 하는 법?

aeronova의 이미지

http://kldp.org/node/72740에 관련된 내용이지만, 새로운 질문이라 새로 글타래를 열었습니다.
Practical C++에 보면 templdate을 사용하더라도 특정 인자의 경우 template이 아닌 special function을 부르게 할 수 있다고 나와있더군요.
(page 440) 그래서 그 예제를 따라해봤는데 특정 인자를 정해준 경우에도 special function이 아닌 templdate이 불려지네요. :(
흠.. 예제가 잘못되었는지요?

// template test
#include <iostream>
#include <cstring>
 
template<typename T>
T max(T d1, T d2) {
        std::cout << "template called" << std::endl;
        if (d1 > d2)
           return (d1);
        return (d2);
}
// A specialization for the "max" function
// because we handle char* a little differently
char* max(char* d1, char* d2) {
        std::cout << "function called" << std::endl;
      if (strcmp(d1,d2) > 0)
         return (d1);
      return (d2);
}
int main(void) {
    // Let's test max
    std::cout << "max(1,2) "  << max(1,2) << std::endl;
    std::cout << "max(\"able\",\"baker\") "  << max("able","baker") << std::endl;    
    return 0;
}

template called
max(1,2) 2
template called
max("able","baker") able
aeronova의 이미지

C++ FAQ에 보니 templdate specialization에 관해 잘 나와 있군요.
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.7
결과적으로 위의 예제 중 두번째 함수는 다음과 같이 되어야 하군요.

template<>
char* max<char*>(char* d1, char* d2) {
      std::cout << "function called" << std::endl;
      if (strcmp(d1,d2) > 0)
         return (d1);
      return (d2);
}

아마 제가 template<> 부분을 빠뜨렸나 봅니다.
...헉, 근데 결과는 이전과 같이 잘못되게 나옵니다.
...아직 뭐가 문제일까요??

It's better to burn out than to fade away. -- Kurt Cobain.

doldori의 이미지

template<typename T>
T max(T d1, T d2); // (1)
 
char* max(char* d1, char* d2); // (2)

일 때 max("able","baker")로 호출하면 당연히 템플릿 함수가 호출됩니다.
인자로 사용된 "able"의 형은 const char[5]이므로 (2)의 인자형과는 맞지 않아서
(1)이 호출되는 것입니다.
const char* max(const char* d1, const char* d2);

로 고치십시오.

만약 함수 템플릿의 specialization을 쓴다면

template<>
const char* max<const char*>(const char* d1, const char* d2);

로 해야 되고요.

ps. 이 코드가 책에 나온 그대로이고 그 결과가

template called
max(1,2) 2
function called
max("able","baker") able

이라고 나와 있다면 별로 좋은 책이 아닙니다.
aeronova의 이미지

감사합니다. 말씀대로 const char* type으로 하니까 원하는 결과가 나옵니다. :)

It's better to burn out than to fade away. -- Kurt Cobain.