函数签名返回摘要 class

Function signature returning abstract class

考虑一些抽象class A:

class A
{
    virtual void f() = 0;
};

假设我希望声明一个返回此 class:

的函数签名类型
using Type = A();

鉴于此代码,gcc-4.8.2 失败并出现错误

error: ‘type name’ declared as function returning an abstract class type

clang-3.3 编译得很好。

我试图 google 这个问题,但没有找到任何有用的东西。此代码是否符合标准?如果不是,禁止声明此类签名类型的原因是什么?我在声明中没有看到任何问题。

免责声明:我不会创建这种类型的实例,我只是想声明一个描述的签名。

对于那些对这种声明的有用性感兴趣的人:我有一些工厂容器在添加新工厂时使用像 Interface(Arguments...) 这样的签名来了解新工厂;实际返回的类型是根据单独的特征 class 确定的,由 Interface.

参数化

显然,我可以将 Interface 与签名分开,但看起来 不好看:(

根据定义,您不能创建抽象对象 class。因此,returning 一个抽象对象的函数是没有意义的。如果您仍想以某种方式 return A,则必须 return 一个指针(实际上必须指向具体子 class 的对象) .

Is this code standard-compliant?

没有。根据 C++11 [class.abstract]/3,"An abstract class shall not be used as a parameter type, as a function return type, or as the type of an explicit conversion."

If not, what is the reasoning behind forbidding declaring such signature type?

该签名的函数不存在,因为它在 return 时必须创建抽象 class 类型的对象。

I don't see any problems in just a declaration.

的确,只是声明是无害的。但这也有些无用;它不会引用任何可能存在的类型。

对于您的用例,您可以使用引用或指针作为 return 类型。