开发者

Specializing function template for both std::string and char*

开发者 https://www.devze.com 2023-02-04 01:06 出处:网络
As the title says I want to specialize a function template for both string and char pointer, so far I did this but I can not figure out passing the string parameters by reference.

As the title says I want to specialize a function template for both string and char pointer, so far I did this but I can not figure out passing the string parameters by reference.

#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::s开发者_C百科tring 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);
} 

Also template<> void xxx<const std::string & >(const std::string & param) thing just does not working.

If I rearranged the opriginal template to accept parameters as T& then the char * is required to be char * & which is not good for static text in code.

Please help !


Doesn’t the following work?

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

And the same for const std::string?

That said, don’t specialize a function template if you have the choice (and you usually do!). Instead, just overload the function:

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

Notice, this is not a template. In 99% of the cases, this is fine.

(Something else, C++ doesn’t have a header <string.h> except for backwards compatibility to C. The C-string header in C++ is called <cstring> (note the leading c) but from your code it look as though you actually mean the header <string> (no leading c).)


Here is a distillation of what I find surprising:

#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) ;
}

This prints "General" 3 times. The first time (float) is expected, the third time (int&) is a surprise. Why doesn't this work?


is really risky try to coding using compiler-based-type-conversions

one thing is the use of a template based, and other is the use of polymorph with different types.

depend of the compiler you can get different behaviors.

0

精彩评论

暂无评论...
验证码 换一张
取 消