Specialized function template for std :: string and char *

As the name says, I want to specialize the function template for both the string pointer and char, so far I have this one , but I can not calculate by passing 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::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); } 

Also template<> void xxx<const std::string & >(const std::string & param) thing just doesn't work.

If I rebuilt the template for accepting parameters as T& , then char * requires char * & , which is not suitable for static text in the code.

Please, help!

+4
source share
3 answers

Does the next job work?

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

And the same for const std::string ?

However, it does not specialize in a function template if you have a choice (and you usually do!). Instead, just overload the function:

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

Please note that this is not a template. In 99% of cases, this is normal.

(Something else, C ++ has no <string.h> header, except for backward compatibility with C. The C-string header in C ++ is called <cstring> (note the leading c ), but from your code it looks like you really mean the header <string> (no leading c ).)

+9
source

Here is a distillation of what I find awesome:

 #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 is this not working?

0
source

really risky trying to code using compiler-based type conversions

one thing is the use of a pattern-based one and the other is the use of a polymorph with different types.

depends on the compiler, you can get different behaviors.

0
source

Source: https://habr.com/ru/post/1335254/


All Articles