Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document opApply as an alias to a function template instance #4142

Open
dlangBugzillaToGithub opened this issue Jun 26, 2024 · 1 comment
Open

Comments

@dlangBugzillaToGithub
Copy link

Bolpat reported this on 2024-06-26T16:29:41Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=24633

CC List

  • Bolpat

Description

When `opApply` is an alias to an explicit function template instance, the explicit instantiation is used for overload resolution against potentially many `opApply` overloads and it is used to infer the types of `foreach` variables, however, the delegate created by the compiler in the `foreach` body lowering is passed to the function template uninstantiated. By this mechanism, when overloading `opApply`s based on the number of intended `foreach` variables, type inference is possible **and** function attributes (e.g. `@safe`) will be inferred.

Example:
```d
struct A
{
    int opApply(scope int delegate(long) body) => body(42);
}
struct B
{
    int opApply(Body)(scope Body body) => body(42);
}
struct C
{
    int opApplyImpl(Body)(scope Body body) => body(42);
    alias opApply = opApplyImpl!(int delegate(long));
}
void main() @nogc nothrow pure @safe
{
    // Error: `@nogc` function cannot call non-@nogc function `A.opApply`
    // Error: `pure` function cannot call impure function `A.opApply`
    // Error: `@safe` function cannot call `@system` function `A.opApply`
    // Error: function `A.opApply` is not `nothrow`
    foreach (x; A()) { }

    // Error: cannot infer type for `foreach` variable `x`
    foreach (x; B()) { }

    // Good:
    foreach (x; C())
    {
        static assert(is(typeof(x) == long));
        assert(x == 42);
    }
}
```

This behavior is great and should be specified as intended.
@dlangBugzillaToGithub
Copy link
Author

dlang-bot commented on 2024-06-26T16:49:30Z

@Bolpat created dlang/dlang.org pull request #3859 "Specify `opApply` as an alias to a function template instance" fixing this issue:

- Fix Bugzilla Issues 23666, 17953, 23116, and 24633

https://github.com/dlang/dlang.org/pull/3859

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant