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

时间:2011-01-12 14:27:15

标签: c++ string templates char

正如标题所说,我想专门为字符串和字符指针设置一个函数模板,到目前为止,我做了this,但我不知道通过引用传递字符串参数。

#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 * &,这对代码中的静态文本不利。

请帮忙!

3 个答案:

答案 0 :(得分: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 :(得分: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) ;
}

这会打印“General”3次。第一次(浮动)是预期的,第三次(int&amp;)是一个惊喜。为什么这不起作用?

答案 2 :(得分:0)

尝试使用基于编译器的类型转换进行编码真的很冒险

一件事是使用基于模板,另一件是使用不同类型的多态。

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