Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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::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 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 !

like image 318
ali_bahoo Avatar asked Dec 28 '22 02:12

ali_bahoo


1 Answers

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).)

like image 184
Konrad Rudolph Avatar answered Dec 30 '22 16:12

Konrad Rudolph