Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 734
Vanwaril Avatar asked Jul 18 '13 07:07

Vanwaril


People also ask

Can template function be overloaded?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

Can overloaded functions have different return types C++?

Function Overloading and Return Type in C++ Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type.

What is the difference between function overloading and function template?

You generally use templates when you want to do the same set of operations on many different data types. You generally would use function overloading when you want to do different operations on certain sets of data.

How many types of templates are there in C++?

There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.


1 Answers

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.

like image 77
ForEveR Avatar answered Oct 16 '22 15:10

ForEveR