Can I define templates for different sets of types?

  • A+

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?


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>{}); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: