Search code examples
d

Abstract auto function in D


Is there any way to have an abstract auto function in D?

If I declare a class as follows:

class MyClass
{
    abstract auto foo();
}

I get the following errors:

main.d(12): Error: function declaration without return type. (Note that constructors are always named 'this')
main.d(12): Error: no identifier for declarator foo()

I'm wondering why this isn't possible? And are there any alternatives to obtain similar functionality?


Solution

  • No, because auto is a placeholder for a static type. The abstract class can't know what the type should be as it's not specified. Even if this did work, foo() may return different types based on its implementations in derived classes. You probably don't want that, since it would mean the API could vary depending on the implementation.

    If you absolutely need this kind of functionality, look at std.variant.