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 !
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
).)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With