是否可以启用,禁用类成员函数?C++启用,禁用类成员函数?
情况: 我有一个类有两种类型。每个类型都有自己的构造函数。一个类型需要一个不能有另一个类型的函数。
例子:
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;
}
};
最简单的将添加一个断言,等待运行时错误。否则,这种事情更多的是通过派生来完成。 –
这将很容易使用不同的类和多态,但我想使用它与相同的名称(在这个例子中的A)和两个同名的类是不可能的。即使他们有不同的构造函数。 – Heinrich
这已经是无效的C++。你有意在那里使用'新'吗? –