1

I want to switch between to members of a templatized class based on the fact the type of the template is default constructible or not.

I think I'm not far from the solution after a lot of reading and tries around std::enable_if and std::is_default_constructible, but I'm still stuck at compile-time, here's a minimized exemple :

template<typename DataType>
class MyClass{

    public:

        template < typename = typename std::enable_if_t<std::is_default_constructible_v<DataType>>>
        inline void createNew(unsigned int index) {
            new (&this->buffer[index]) DataType(); // "placement new"
        }

        template < typename = typename std::enable_if_t<!std::is_default_constructible_v<DataType>>>
        inline void createNew(unsigned int index) {
            throw BaseException("No default constructor");
        }
};

This last try results on "member function already defined or declared". I think I miss something, but I don't understand why both functions are selected for compilation even if they have the exact opposite template condition.

SamT
  • 528
  • 4
  • 14
  • 1
    Your two overloads differ only by their default template _arguments_, and default template arguments are not part of a function template's signature, meaning these two overloads have the same signature. Instead of using the `typename = typename std::enable_if_t<...>` approach (applying SFINAE to the default template _argument_), you may use the alternative approach `std::enable_if_t<...>* = nullptr>` to make the SFINAE construct a part of the template parameters (as a non-type template parameter), which _is_ naturally part of the function signature. – dfrib May 18 '20 at 11:05
  • I succeed doing this using the attached similar question. This results in this : template , bool>::type = true> – SamT May 19 '20 at 12:11
  • Yes, you are then using the approach I mentioned in my previous comment, placing the SFINAE construct as a (non-type) template _parameter_ instead of as a default template _argument_; note that you are simply using a `` non-type template parameter approach rather than `` non-type template parameter approach (my comment above). – dfrib May 19 '20 at 13:13

0 Answers0