c++struct

Why can't I call a member function on an unnamed struct?


This code:

int main() {
    auto value = struct {
        int test() {
            return 1;
        }
    }().test();
}

While odd seems to me like it should be an expression, and yet:

<source>:2:18: error: expected expression
    2 |     auto value = struct {
      |                  ^
1 error generated.

My use case for this is to be able to declare a struct in a macro and execute a function from it (static or not) so that I can do some additional template magic while avoiding any implicit capture behavior of a lambda.


Solution

  • You can't because C++ is specified that way. There is no good reason why defining types in-place isn't allowed, perhaps it's just historical cruft.

    However, you can define a named struct inside a lambda, then create and return an instance of it:

    int main() {
        auto value = [](){
            struct dummy {
                int test() {
                    return 1;
                }
            };
            return dummy{};
        }().test();
    }