gpt4 book ai didi

c++11 - 如何在类声明之外定义 sfinae 类的成员?

转载 作者:行者123 更新时间:2023-12-02 04:01:26 36 4
gpt4 key购买 nike

阅读诸如 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) 来编译此代码。

最佳答案

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

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

关于c++11 - 如何在类声明之外定义 sfinae 类的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41708870/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com