如何使用 std::enable_if 为 class 专门定义 class 函数

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

我有一个名为 graph 的 class 专业化,它仅在输入为特定类型时才启用。我无法为 class 中的函数定义超出 class 的定义。 这个问题 os 不同于其他一些关于堆栈溢出的问题,其中 sfinae 发生在成员函数上。在这里我想在 class 上启用 if 并且只在 class.

之外为这个 class 定义一个普通成员函数

注意 - 有多个图表 classes 具有不同的容器类型。这只是一个例子。

我希望能够在此 class 之外定义 graph_func

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

我试过了,但出现错误,它没有引用任何 class

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

请注意,您的参数列表中的 std::enable_if<..., int>::type 是一个 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;
};

你需要将那个类型的(这里我们只是命名为_)传递给参数列表:

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

live demo.