2
#include<iostream>

using namespace std;

// define the general compare template
 template <class T>
 int compare(const T& t1, const T& t2) {
   cout<< "Common_T"<<endl;
   return 0;

 }
 template<>
 int compare<const char*>( const char * const& s1,
                          const char * const& s2)
 {
    cout<< "Special_T"<<endl;
    return 0;
 }
typedef const char  char6[6];
     template<>
             int compare<char6>(const char6& s1,const char6& s2)
    {
            cout << "Special_Char6_T" << endl;
             return 0;
    }

 int main() {
     int i = compare("hello" , "world");
 }

结果是:

Common_T

我的问题是:为什么不输出“Special_Char6_T”???

4

2 回答 2

1

This is the correct template specialization that matches your c strings.

typedef char char6[6];
template<> int compare<char6>(char6 const &s1,char6 const &s2)
{
    cout << "Special_Char6_T" << endl;
    return 0;
}
于 2012-08-02T05:51:21.850 回答
-1

Intuitively, because the dimension of arrays is not part of their type. That dimension matters only for variables and fields. So both

  char hello[6]="hello";

and

  char longstring[] = "a very very long string should be here";

have both the same type char[]

and

 typedef char t1[6];

and

 typedef char t2[];

are aliases for the "same" type.

(You could look at the mangled function names to have a clue)

于 2012-08-02T05:50:37.847 回答