Home > database >  Function template selected instead of specific std::string overload when called with a string litera
Function template selected instead of specific std::string overload when called with a string litera

Time:08-16

I have the following function template in one of my classes:

template<typename T> void Add(T data) { memcpy(cursor, &data, sizeof(T)); }

It works, but it is not adapted to std::string, for which the correct function would be:

void Add(string data) { memcpy(cursor, data.c_str(), data.size()); }

Unfortunately if I call the function with a string

Add("my text");

the function called is the one generated by the template. Is there a way to give my own function priority for specific types? Can I overload the function generated by the template somehow? I've tried some hacky stuff with std::is_same, std::enable_if_t, and other things but nothing seems to quite work.

CodePudding user response:

My mistake, when passing a string directly by doing Add("my text") the type is actually const char* overloading the template with a function void Add(const char*) { ... } solved the issue.

CodePudding user response:

try to use template partitial specialization:

template <typename T>
void Add(T data) { 
  memcpy(cursor, &data, sizeof(T)); 
}

// partitial version
template <>
void Add(std::string data) { 
  memcpy(cursor, data.c_str(), sizeof(T)); 
}
  • Related