Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function signature returning abstract class

Consider some abstract class A:

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

Suppose I wish to declare a function signature type returning this class:

using Type = A();

Given this code, gcc-4.8.2 failes with error

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

clang-3.3 compiles this nicely.

I tried to google this issue, but failed to find anything usefull. Is this code standard-compliant? If not, what is the reasoning behind forbidding declaring such signature type? I don't see any problems in just a declaration.

Disclaimer: I am NOT going to create instances of this type, I'm just interested in declaring a signature described.

For those interested in usefullness of such a declaration: I have some factory container that uses a signature like Interface(Arguments...) when adding new factories to learn something about the new factory; the actual returned type is determined based on a separate traits class, parametrised by Interface.

Obviously, I can just separate Interface from signature, but it won't look that nice :(

like image 830
lisyarus Avatar asked Jan 17 '26 02:01

lisyarus


1 Answers

Is this code standard-compliant?

No. According to 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?

A function of that signature can't exist, since it would have to create an object of an abstract class type when it returns.

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

Indeed, just a declaration would be harmless. But it would also be somewhat useless; it wouldn't refer to any type that can exist.

For your use-case, you could use a reference or pointer as the return type.

like image 124
Mike Seymour Avatar answered Jan 19 '26 18:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!