如何使用nullary成员函数的Sfinae

How to use SFINAE with nullary member function?

本文关键字:Sfinae 函数 成员 何使用 nullary      更新时间:2023-10-16

我有一个带有布尔模板参数can_fly的类模板Bird。根据该值,我想启用具有签名void fly();的成员函数。

这是我的代码:

#include <type_traits>
template<bool can_fly>
class Bird {
public:
    template<typename void_t = typename std::enable_if<can_fly>::type>
    void_t fly() { /* ... */ }
};
int main() {
    Bird<true> flyingBird;
    flyingBird.fly();
    Bird<false> flightlessBird;
    return 0;
}

此代码在Visual Studio 2015中编译了罚款,但GCC抱怨说," note in struct std :: enable_if''"在main的第三行中"。

我认为false情况下没有::type的事实是Sfinae的全部点。有人可以向我解释我做错了什么,正确的方法是什么?

,如下所述:

enable_if起作用是因为替换模板参数导致错误,因此从过载分辨率集中删除替换,并且编译器仅考虑其他可行的过载。

在您的情况下,由于can_fly在实例化时是已知的,因此没有替代。您可以创建一个虚拟默认bool模板参数以使Sfinae正常工作:

template<bool can_fly>
class Bird {
public:
    template<bool X = can_fly, typename = typename std::enable_if<X>::type>
    void fly() { /* ... */ }
};

wandbox示例