Bonjour,
voici un petit bout de code dont je ne m'explique pas le comportement.
Mon but initial était d'avoir une fonction template avec une version spécialisée pour les types "simples" (ie non pointés), les pointeurs et les char* en particulier.
Voici le code :la sortie ressemble à ça
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 class Foo { public: Foo ( int x , int y ) : x(x),y(y) {} template <class OUT> friend OUT & operator<< ( OUT & output , const Foo & f ) { output << f.x << ',' << f.y ; return output ; } protected: int x,y ; }; #include <iostream> using namespace std ; template<class T> T Bare ( T x ) { cout << "simple : " ; return x ;} template<class T> T Bare ( T * x ) { cout << "pointer : " ; return *x ;} template<> char* Bare ( char * x ) { cout << "char* : " ; return x ;} template<> const char* Bare ( const char * x ) { cout << "cst char* : " ; return x ;} template<class T> void Spam ( T x ) { cout << "simple : " << x << endl ;} template<class T> void Spam ( T * x ) { cout << "pointer : " << *x << endl ;} template<> void Spam ( char * x ) { cout << "char* : " << x << endl ;} template<> void Spam ( const char * x ) { cout << "cst char* : " << x << endl ;} template<class T> void SuperSpam ( T x ) { cout << Bare( x ) << " ---> " ; Spam( x ) ;} int main () { const char s [] = "0123456789" ; int x = 123 ; const int * y = &x ; Foo f( 465,789 ) ; SuperSpam( 3 ) ; SuperSpam( y ) ; SuperSpam( f ) ; SuperSpam( &f ) ; SuperSpam( "text" ) ; SuperSpam( s+3 ) ; }Ma question :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6 simple : 3 ---> simple : 3 pointer : 123 ---> pointer : 123 simple : 465,789 ---> simple : 465,789 pointer : 465,789 ---> pointer : 465,789 pointer : t ---> cst char* : text pointer : 3 ---> cst char* : 3456789
pourquoi Bare ne reconnaît pas les char* (ils sont assimilés à des pointeurs "ordinaires") alors que Spam fait bien la différence ?
Mystère et boucle de gomme++
Partager