如何使用nullary成员函数的Sfinae
How to use SFINAE with nullary member function?
我有一个带有布尔模板参数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示例
相关文章:
- 为什么使用SFINAE而不是函数重载
- 如何使用模板函数的函数签名进行SFINAE
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 基于 SFINAE 的特征实现问题与函数模板重载
- 函数模板实例化的 sfinae
- 使用表达式 SFINAE 的函数模板的类外定义
- C++SFINAE enable_if_t成员函数,如何消除歧义?
- 使用SFINAE来检测void返回类型函数的存在
- 构造函数SFINAE和继承在clang中失败
- 关于SFINAE的函数和结构之间的差异
- C++:SFINAE 来区分填充和范围构造函数?
- 使用 SFINAE 有选择地实例化模板的成员函数
- SFINAE 用于具有默认参数的函数对象
- SFINAE 和模板函数实例化:为什么在启用了 SFINAE 类型的函数参数中使用模板参数时无法推断模板参数?
- SFINAE :删除具有相同原型的函数
- 检查类型 T 是否具有成员函数 SFINAE 的任何重载
- SFINAE :知道一个函数是否已经存在
- Constexpr 函数作为 SFINAE 的模板参数
- 简单的 SFINAE 示例以重载函数不编译