2011-01-12 4 views
4

제목에 문자열과 문자 포인터에 대한 함수 템플릿을 특수화하고 싶다고 말하면서 지금까지 this을 수행했지만 참조로 문자열 매개 변수를 전달할 수 없습니다 .std :: string 및 char에 대한 특수 함수 템플릿 *

#include <iostream> 
#include <string.h> 
template<typename T> void xxx(T param) 
{ 
std::cout << "General : "<< sizeof(T) << std::endl; 
} 

template<> void xxx<char*>(char* param) 
{ 
std::cout << "Char ptr: "<< strlen(param) << std::endl; 
} 

template<> void xxx<const char* >(const char* param) 
{ 
std::cout << "Const Char ptr : "<< strlen(param)<< std::endl; 
} 

template<> void xxx<const std::string & >(const std::string & param) 
{ 
std::cout << "Const String : "<< param.size()<< std::endl; 
} 

template<> void xxx<std::string >(std::string param) 
{ 
std::cout << "String : "<< param.size()<< std::endl; 
} 


int main() 
{ 
     xxx("word"); 
     std::string aword("word"); 
     xxx(aword); 

     std::string const cword("const word"); 
     xxx(cword); 
} 

또한 template<> void xxx<const std::string & >(const std::string & param) 일이 제대로 작동하지 않습니다.

파라미터를 T&으로 허용하도록 원래 템플릿을 재정렬하면 char *은 코드의 정적 텍스트에는 적합하지 않은 char * &이어야합니다.

도와주세요!

+1

이제 컴파일되지 않습니다! 'strlen'을 위해서''을 되돌려 주어야합니다. – TonyK

답변

9

다음 작업을 수행 할 수 없습니까?

template<> 
void xxx<std::string>(std::string& param) 
{ 
    std::cout << "String : "<< param.size()<< std::endl; 
} 

const std::string?

그렇다면, don’t specialize a function template 선택 사항이 있다면 (보통 그렇습니다!). 대신에, 단지 기능에 과부하 :

void xxx(std::string& param) 
{ 
    std::cout << "String : "<< param.size()<< std::endl; 
} 

공지 사항,이 하지 템플릿입니다. 99 %의 경우에는 괜찮습니다.

(뭔가 다른, C++은 C에서 C로 C 문자열 헤더에 이전 버전과의 호환성을 제외한 헤더 <string.h>이없는 ++ (주요 c주의) <cstring>라고하지만 사용자 코드에서 당신이 실제로 의미하는 것처럼 보이는됩니다 .

#include <iostream> 

template<typename T> void f(T param) { std::cout << "General" << std::endl ; } 
template<> void f(int& param) { std::cout << "int&" << std::endl ; } 

int main() { 
    float x ; f (x) ; 
    int y ; f (y) ; 
    int& z = y ; f (z) ; 
} 

이 인쇄 "일반"3 회 : 헤더 <string>는 (아무 c을 선도)) 다음은

+1

아, 죄송합니다. ''. 나는 고칠 것이다. –

+5

링크가 특수하지 않아야하는 이유는 좋을 것입니다. 여기 http://www.gotw.ca/publications/mill17.htm – stefaanv

+1

@stefaanv : nice가 포함됩니다. –

0

나는 놀라운 무엇을 발견의 증류이다. 처음으로 (float) 예상되며 세 번째로 (int &) 놀랍습니다. 왜이 기능이 작동하지 않습니까?

+0

이것은 std :: string &에 문제가 있습니다. 템플릿에서 참조 된 유형을 전달하는 데 문제가 있습니다. 누군가가 설명해주기를 바랍니다. –

0

사용하여 컴파일러 기반 형 - 변환을 기반으로 템플릿의 사용

한 가지를 코딩 정말 위험한 시도이고, 다른 하나는 다른 유형의 형체를 사용하는 것입니다.

컴파일러에 따라 다른 동작을 얻을 수 있습니다.

관련 문제