I need to write a templated function, that behaves differently depending on the class of its parameter:
template<class ContainerType>
bool myFunc(ContainerType in){
//do some stuff
}
template<class NotAContainerType>
bool myFunc(NotAContainerType in){
//do something else
}
I am restricted to C++11, so static_if
is off the table. Also, the classes of ContainerType
and NotAContainerType
are really large and might change in the future, so just adding a few exceptions by hand as a template specialization is not sensible either.
I am aware of the std::enable_if
workaround, but how do I use it, if I need to apply it to two mutually distinct sets of classes?
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
There are three kinds of templates: function templates, class templates and, since C++14, variable templates.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
If we want to define a different implementation for a template when a specific type is passed as template parameter, we can declare a specialization of that template.
Create a traits for your concept Container, then, you might use SFINAE
template <typename T>
typename std::enable_if<is_container<T>::value, bool>::type
myFunc(T in){
//do some stuff
}
template <typename T>
typename std::enable_if<!is_container<T>::value, bool>::type
myFunc(T in){
//do some stuff
}
or tag dispatching
namespace details
{
template <typename T>
bool myFunc(T in, std::true_type){
//do some stuff
}
template <typename T>
bool myFunc(T in, std::false_type){
//do some stuff
}
}
template <typename T>
bool myFunc(T in){
return details::myFunc(in, is_container<T>{});
}
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