vladon
vladon

Reputation: 8401

Select class constructor

I want to make class template constructor default if it is trivial and default for T, something like this:

template <typename T>
class my_class {
public:
    template <typename <std::enable_if<std::is_trivially_default_constructible<T>::value, int>::type = 0>
    constexpr my_class() = default;

    template <typename <std::enable_if<!std::is_trivially_default_constructible<T>::value, int>::type = 0>
    constexpr my_class() {};
}

Of course, this code does not work (empty parameter if condition does not met). How to do it?

Upvotes: 0

Views: 95

Answers (1)

TartanLlama
TartanLlama

Reputation: 65620

You can provide separate specializations for when T is and is not trivially default-constructible:

template <typename T, bool = std::is_trivially_default_constructible<T>::value>
class my_class {
public:
    constexpr my_class() = default;
};

template <typename T>
class my_class<T, false> {
public:
    constexpr my_class() {};  
};

Upvotes: 2

Related Questions