Home > Back-end >  Template specialization for constructor based on type
Template specialization for constructor based on type

Time:03-17

I've been looking for this for quite a while, and I maybe I just don't know what words to use to find it.

I have a template class that accepts a type, and would like the constructor to be different depending on if that type is a pointer or not. Here is some code to explain what I mean.

template <class T> class Example
{
    bool choice;
public:
    //Only if T is not a pointer type
    Example() : choice{false}
    {}

    //Only if T is a pointer type
    Example(bool choice) : choice{choice}
    {}
}

I have experimented with std::enable_if and std::is_pointer<T> but with no luck.

CodePudding user response:

You can either specialize the whole class:

template <class T> struct Example {
    bool choice;
    Example() : choice{false} {}
};

template <class T> struct Example<T*> {
    bool choice;
    Example(bool choice) : choice{choice} {}
};

int main() {

    Example<int> e;
    Example<int*> f(false);
}

Or via std::enable_if:

#include <type_traits>

template <class T> struct Example {
    bool choice;

    template <typename U = T, std::enable_if_t<!std::is_pointer_v<U>,bool> = true>
    Example() : choice{false} {}

    template <typename U = T, std::enable_if_t<std::is_pointer_v<U>,bool> = true>
    Example(bool choice) : choice{choice} {}
};

int main() {
    Example<int> e;
    Example<int*> f(false);
}

Only one of the conditions for std::enable_if is true. Either std::is_pointer_v<T> is true then the first constructor is a substitution failure or it is false then the second is discarded.

  •  Tags:  
  • c
  • Related