Vanwaril
Vanwaril

Reputation: 7528

Overload Templated Function for All String Types

I have the following template:

template<class T>
void fn(T t){ }

and I'd like to override its behavior for anything that can be converted to std::string.

Both specifying an explicit template specialization and a non-template function overload with the parameter as an std::string only work for calls that pass in an std::string and not other functions, since it seems to be matching them to the template before attempting argument conversion.

Is there a way to achieve the behavior I want?

Upvotes: 5

Views: 83

Answers (1)

ForEveR
ForEveR

Reputation: 55887

Something like this case help you in C++11

#include <type_traits>
#include <string>
#include <iostream>

template<class T>
typename std::enable_if<!std::is_convertible<T, std::string>::value, void>::type
fn(T t)
{
   std::cout << "base" << std::endl;
}

template<class T>
typename std::enable_if<std::is_convertible<T, std::string>::value, void>::type
fn(T t) 
{
   std::cout << "string" << std::endl;
}

int main()
{
   fn("hello");
   fn(std::string("new"));
   fn(1);
}

live example

And of course, you can realize it manually, if you have no C++11, or use boost.

Upvotes: 9

Related Questions