是否可以启用、禁用类成员函数?
情况:我有一堂有两种类型的课。每个类型都有自己的构造函数。一种类型需要一个不能具有另一种类型的功能。
例子:
class A {
enum struct TypeEnum : int {
TYPE_1 = 1,
TYPE_2 = 2
};
const TypeEnum type;
int x;
A(void) : type(TypeEnum::TYPE_1) { }
A(int _x) : type(TypeEnum::TYPE_2) {
x = _x;
}
// function only for Type 2
void A::operator += (const int& n) {
x = x + n;
}
};
int main() {
A test1 = new A();
A test2 = new A(1);
test1 += 5; // compiler error should be here
test2 += 5; // OK
return 0;
}
有可能是这样的:
class A {
enum struct TypeEnum : int {
TYPE_1 = 1,
TYPE_2 = 2
};
const TypeEnum type;
int x;
A(void) : type(TypeEnum::TYPE_1) { }
A(int _x) : type(TypeEnum::TYPE_2) {
x = _x;
}
// Is somethig like this realy impossible
void A::operator += (const int& n) -> enable_if(type == TypeEnum::Type2) { // if not compile error
x = x + n;
}
};