Specializing function template for both std::string and char*
Posted
by
sad_man
on Stack Overflow
See other posts from Stack Overflow
or by sad_man
Published on 2011-01-12T14:27:14Z
Indexed on
2011/01/12
14:53 UTC
Read the original article
Hit count: 153
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>
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 !
© Stack Overflow or respective owner