专门针对std :: string和char*的函数模板

ali*_*hoo 4 c++ string templates 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);
} 
Run Code Online (Sandbox Code Playgroud)

另外template<> void xxx<const std::string & >(const std::string & param)一点就是不工作.

如果我重新安排opriginal模板接受参数,T&char *需要对char * &代码中的静态文本不利.

请帮忙 !

Kon*_*lph 9

以下工作没有?

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

同样的const std::string

也就是说,如果你有选择的话,不要专门化一个功能模板(你通常会这样做!).相反,只是重载函数:

void xxx(std::string& param)
{
    std::cout << "String : "<< param.size()<<  std::endl;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这不是模板.在99%的情况下,这很好.

(<string.h>除此之外,C++ 除了向后兼容C之外没有标题.C++中的C字符串标题被调用<cstring>(注意前导c)但是从你的代码看起来好像你实际上是指标题<string>(没有前导c). )

  • 关于为什么它不应该专门化的链接会很好,所以这里是:http://www.gotw.ca/publications/mill17.htm (5认同)
  • @sad_man:不,这是康拉德斯的答案,说实话,我以前没有意识到这一点...... (2认同)
  • 你编译过这个吗?g ++ 4.4.0不接受它.它给出了错误消息:'error:template-id'xxx <std :: string>'for'void xxx(std :: string&)'与任何模板声明都不匹配 (2认同)