在运行时检查我是否可以实例化(抽象)类
Check at runtime if I can or cannot instantiate (abstract) class
假设我有:
class A:
{
public:
A();
virtual void foo();
};
class B:public A
{
public:
B();
void foo();
};
class C:public A
{
public:
C();
void foo();
};
和在主要
if(is_abstract<A>::value==false)
{
int option;
cout<<"What type of object do you want to create? 0-A,1-B,2-C";
cin option;
if(option==0)
A *a = new A();
if(option==1)
B *b = new B();
else
C *c = new C();
}
else
{
int option;
cout<<"What type of object do you want to create? 1-B,2-C";
cin option;
if(option==1)
B *b = new B();
else
C *c = new C();
}
在当前状态下,代码将起作用。如果我使虚拟 void foo()=0,A 成为抽象类,并且我得到编译时错误,因为我无法在 A *a = new A() 处实例化抽象类。有没有办法绕过这个编译时错误?谢谢
在当前形式中,将生成尝试实例化 A 的代码(尽管从未调用)。即使编译器由于优化而不会生成代码,未生成的代码仍然必须是有效的,而你的则不是。
要解决它,您必须使用某种形式的 SFINAE 来确保永远不会生成尝试实例化 A 的代码。像这样:
void make(std::enable_if_t<std::is_abstract<A>::value>* = nullptr) {
... (the code which never creates A)
}
void make(std::enable_if_t<!std::is_abstract<A>::value>* = nullptr) {
... (the code which does create A)
}
...
make();
相关文章:
- ATL::CComContainedObject<contained>: C2259 无法实例化抽象类
- 如何使用其中一个具体类实例化抽象类?
- 无法实例化抽象类错误
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 'AMA::我的产品':无法实例化抽象类
- 无法实例化抽象类
- 如何修复错误C2259:无法实例化抽象类
- C++,不能实例化抽象类
- 无法使用多重继承 c++ 实例化抽象类
- 无法实例化抽象类
- C++,无法实例化抽象类错误
- C2259:'ATL::CComObject<Base>':无法实例化抽象类
- 错误 C2259:'CDocument':无法实例化抽象类
- 帮助错误 C2259:无法实例化抽象类
- 无法实例化抽象类
- 错误 C2259"类":无法实例化抽象类
- 不能实例化抽象类的对象,但必须返回该类的对象
- 继承错误 - 无法实例化抽象类 无法访问在类中声明的受保护成员
- 无法使用 c++11 实例化抽象类
- 创建 CTI 适配器时无法实例化抽象类