在运行时检查我是否可以实例化(抽象)类

Check at runtime if I can or cannot instantiate (abstract) class

本文关键字:实例化 抽象 运行时 检查 是否      更新时间:2023-10-16

假设我有:

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();