c++ - C++ 此代码如何工作(enable_if 构造函数/方法)?
问题描述
我知道这两个主题之前已经讨论过,但是我仍然不清楚构造函数的启用和方法的启用是如何工作的。
这是我创建的一个很好的清晰示例。
#include <type_traits>
#include <string>
#include <iostream>
template<bool B> using EnableConstructorIf = typename std::enable_if<B, int>::type;
template<bool B, class T> using EnableMethodIf = typename std::enable_if<B,T>::type;
template <int N>
class MyClass {
public:
std::string s;
template<int M=N, EnableConstructorIf< (M<0) > = 0> MyClass() {
s = "Negative";
}
template<int M=N, EnableConstructorIf< (M==0) > = 0> MyClass() {
s = "Zero";
}
template<int M=N, EnableConstructorIf< (M>0) > = 0 > MyClass() {
s = "Positive";
}
template<int M=N> EnableMethodIf< (M<0), int> getSign() {
return -1;
}
template<int M=N> EnableMethodIf< (M==0), int> getSign() {
return 0;
}
template<int M=N> EnableMethodIf< (M>0), int> getSign() {
return +1;
}
};
int main(int argc, char *argv[])
{
using namespace std;
MyClass<-5> a;
MyClass<0> b;
MyClass<100> c;
cout << "a.string = " << a.s <<" ->"<< a.getSign() << endl;
cout << "b.string = " << b.s <<" ->"<< b.getSign() << endl;
cout << "c.string = " << c.s <<" ->"<< c.getSign() << endl;
return 0;
}
正如预期的那样,它编译并产生以下输出。但它是如何工作的?
a.string = Negative ->-1
b.string = Zero ->0
c.string = Positive ->1
解决方案
推荐阅读
- plugins - 如何从 WebStorm IDE 中禁用或删除插件
- batch-file - 无法从 .bat 文件启动具有不同选项的程序
- arrays - NSMutableAttributedString 到一个数组
- javascript - 为什么使用 Ajax 响应重新加载整个页面时 Jquery 不起作用?
- html - 如何保持模式?
- python - 关于使用您自己的模块时硬编码变量的最佳实践的问题
- php - 带有foreach的数组中的PHP更改顺序
- node.js - Lerna 提升不适用于非同级文件夹或位于 packages 文件夹内的文件夹。
- php - 使用 PHP 在 JSON 中追加新数据
- r - 使用从 R 中的向量创建的名称分配给对象