如何为专用于 std::enable_if 的类定义类外函数

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

本文关键字:if 定义 函数 enable 专用 用于 std      更新时间:2023-10-16

我有一个叫做图的类的专门化,只有当输入是特定类型时才会启用。我无法为该类中的函数定义类外定义。这个问题不同于堆栈溢出的其他一些问题,其中 sfinae 发生在成员函数上。在这里,我希望在类上启用,并且只在类外为该类定义一个普通成员函数。

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

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

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

我试过这个,但出现错误,它没有引用任何类

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是非类型模板参数:

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
}

观看现场演示。