Search code examples
c++templatesinheritancetemplate-meta-programmingsfinae

How to use SFINAE with a child class


I have a non-template parent interface and am trying to use SFINAE on a child class. All I want to do is verify the type of the first template parameter can be constructed without any arguments. My issue is in forward declaration. Based on my understanding, SFINAE requires a class to be forward declared and then specialized. This is currently what I'm trying:

class ParentInterface
{};

template<class, class = void>
class Child : public ParentInterface; // <-- This semi-colon is the error

template<class Ty>
class Child<Ty, std::enable_if_t<std::is_constructible_v<Ty>>>
    : public ParentInterface
{};

The answers I was able to find related to this had to do with inheriting from a SFINAE class. What do I need to do to get my intended functionality?


Solution

  • template<class, class = void> class Child : public ParentInterface;

    is neither a declaration nor definition.

    You probably want declaration:

    `template<class, class = void>
    class Child;
    

    And then you can add your partial specialization definition:

    template<class Ty>
    class Child<Ty, std::enable_if_t<std::is_constructible_v<Ty>>>
        : public ParentInterface
    {};