Search code examples
c++template-meta-programmingsfinaegeneric-programmingpartial-specialization

How to define out of class functions for a class specialized using std::enable_if


I have a specialization of a class called graph which is enabled only if the input is a particular type. I am not able to define out of class definitions for the functions inside that class. This question os different from some other questions on stack overflow where sfinae happens on member function. Here I want enable if on the class and just define a normal member function for this class outside the class.

Note- There are multiple graph classes with different container types. This is an example of just one.

I want to be able to define graph_func outside this class

template<typename ContainerType,
    std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type = 0>
class graph
{
    .
    .
    .
    void graph_func() const;
}

I tried this and I get the error that it doesn't refer into any class

template <typename ContainerType>
void graph<ContainerType,  std::enable_if<std::is_same<Graph, Eigen::MatrixXd>::value, int>::type>::graph_func() const
{
  // definition
}

Solution

  • Notice that std::enable_if<..., int>::type in your parameter list is an non-type template argument:

    template<typename ContainerType,
        typename std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type = 0>
    class graph
    {
        void graph_func() const;
    };
    

    You need to pass the value of that type (In here we just named it _) to the parameter list:

    template <typename ContainerType,
        typename std::enable_if<std::is_same<ContainerType, Eigen::MatrixXd>::value, int>::type _>
    void graph<ContainerType, _>::graph_func() const
    {
      // definition
    }
    

    See live demo.