2011-01-12 55 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)事情只是不工作。

如果我重新排列了opriginal模板以接受参数T&,那么char *需要为char * &,这对代码中的静态文本不利。

请帮忙!

+1

现在它不编译!你需要把``放回``strlen`。 – TonyK 2011-01-12 16:39:12

回答

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++没有一个头<string.h>除了向后兼容性在C C的C-串头++被称为<cstring>(注意龙头c),但是从你的代码,它看起来好像你真正的意思。头<string>(无领导c))

+1

对不起``。我会修好它。 – 2011-01-12 14:36:55

+5

链接是,为什么它不应该被专门不错,所以在这里它是:http://www.gotw.ca/publications/mill17.htm – stefaanv 2011-01-12 14:48:40

0

这里是什么,我觉得奇怪的蒸馏:

#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倍。第一次(浮动)预计,第三次(int &)是一个惊喜。为什么这不起作用?

0

真的是有风险的尝试编码使用的编译型型转换

一件事是使用基于模板的,以及其他与不同类型的使用多晶型的。

依赖于编译器,你可以得到不同的行为。

相关问题