[Issue 10846] New: Allow defining functions in enum declarations

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Aug 18 15:06:41 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=10846

           Summary: Allow defining functions in enum declarations
           Product: D
           Version: unspecified
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: andrej.mitrovich at gmail.com


--- Comment #0 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2013-08-18 15:06:39 PDT ---
Currently, thanks to UFCS, we can define most functions in module scope and
make them act as if they were member functions. However this doesn't work
nicely when you have multiple functions with the same name in different
modules, for example:

-----
module a;
import b;
struct A { }
void test(A a) { }

void main()
{
    B b;
    b.test();
}
-----

-----
module b;
struct B { }
void test(B b) { }
-----

$ dmd -c a.d
> a.d(9): Error: function a.test (A a) is not callable using argument types (B)

This is D's protection against function hijacking. The diagnostic should
improve, but that's beside the point.

To work around this (without being forced to merge overloads with alias
declarations), one can define these functions inside the structures, and there
will be no errors:

-----
module a;
import b;
struct A { void test() { } }

void main()
{
    B b;
    b.test();
}
-----

-----
module b;
struct B { void test() { } }
-----

$ dmd -c a.d
>

This could also be considered a more "tightly" coupling.

However, we cannot use this with enums because enums cannot have functions as
members. So the following code becomes an error:

-----
module a;
import b;

enum EA { a }

void test(EA a) { }

void main()
{
    EB eb;
    eb.test();
}
-----

-----
module b;

enum EB { b }

void test(EB eb) { }
-----

$ dmd -c a.d
> a.d(11): Error: function a.test (EA a) is not callable using argument types (EB)

The way to work around this is to merge the overloads with alias declarations.

But if functions inside of enums were allowed, then we could have a simpler
workaround for the function hijacking protection.

Unfortunately I can't think of a way to make the syntax look nice, for example:

-----
enum E 
{ 
    a,
    b,
    c,
    void test() { }  // looks awkward
}
-----

It looks weird to have a function embedded next to the members.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list