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?
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.
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.
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.
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.
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.
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