【问题标题】:How to define member of sfinae class outside of class declaration?如何在类声明之外定义 sfinae 类的成员?
【发布时间】:2017-06-02 05:00:45
【问题描述】:

在阅读了诸如sfinae on member function defined outside of class body(这不是同一个问题)之类的问题后,当使用 SFINAE 方法时,我仍然没有得到在类声明之外定义成员函数体的好方法仅使用算术类型启用该类。

#include <type_traits>

template <typename T,typename = typename std::enable_if<std::is_arithmetic<T>::value,T>::type>
class foo
{
public:
    void bar();
};

template <typename T>
void foo<T>::bar ()
{
}

在这个例子中,我得到了错误:

error: invalid use of incomplete type 'class foo<T>'
void foo<T>::bar ()
^
error: declaration of 'class foo<T>'
class foo
^

如果我这样声明:

#include <type_traits>

template <typename T,typename = typename std::enable_if<std::is_arithmetic<T>::value,T>::type>
class foo
{
public:
    void bar()
    {
    }
};

它运行起来没有任何问题。

我正在使用 mingw-w64 (w64 3.3) 来编译这段代码。

【问题讨论】:

    标签: c++11 templates sfinae


    【解决方案1】:

    foo 有两个模板参数,即使其中一个未命名、默认并用于 SFINAE。因此:

    template <typename T, typename U>
    void foo<T, U>::bar ()
    {
    }
    

    【讨论】:

    • 在这种情况下,如果你声明一个以两个 foo 作为 const ref 参数的函数,你不需要指定第二个 typename ?
    • @PierreAntoineGuillaume 如void baz(foo&lt;int&gt; const &amp;) ?那是因为它只是使用(实例化)foo。另一方面,定义foo 要求您明确说明您所关注的foos 的哪一部分。您的语法可能意味着“使用默认参数”,但在您的情况下,您将定义部分专业化 (foo&lt;T, void&gt;)、which is not permitted 的单个成员函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 2020-07-31
    • 1970-01-01
    • 2012-08-04
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多