Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define templates for different sets of types?

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?

like image 502
Jonn Dove Avatar asked Jul 25 '18 08:07

Jonn Dove


People also ask

How will you restrict the template for a specific datatype?

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.

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.

What is the difference between class template and function template?

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.

How can you define an implementation of a template when a specific type is passed as template parameter?

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.


1 Answers

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>{});
}
like image 155
Jarod42 Avatar answered Oct 07 '22 18:10

Jarod42