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.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.