【问题标题】:How to define out of class functions for a class specialized using std::enable_if如何为使用 std::enable_if 专门的类定义类外函数
【发布时间】:2019-08-31 04:43:06
【问题描述】:

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

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

我希望能够在这个类之外定义 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
}

【问题讨论】:

  • 您可以将您的专业化定义简化为template &lt;&gt; class graph&lt;Eigen::MatriXd&gt;,没有理由使用 SFINAE。如果要将ContainerType 限制为Eigen::MatrixXd,则使用static_assert,或者根本不使用模板
  • 我必须使用 SFINAE,因为我有针对不同容器类型的多个图类专业化。我认为我不能使用静态断言,因为这会在类选择之后发生,并且会从选择中消除其他专业化。
  • 这应该包含在问题本身中,因为与您编写的代码一起,这一切都变得不清楚。

标签: c++ template-meta-programming sfinae generic-programming partial-specialization


【解决方案1】:

请注意,您的参数列表中的std::enable_if&lt;..., int&gt;::typenon-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.

【讨论】:

    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多