Why can't the type of my class-static auto function be deduced within the class scope?
Asked Answered
T

1

11

I'm trying to get the return type of an auto function. This works:

auto foo(int bar)
{
    return 0;
}

typedef std::result_of<decltype(foo)> foo_t;

Great, here's the next step then: getting the return type of a static auto function in a class scope. This also works:

struct Foo
{
    static auto foo(int bar)
    {
        return 0;
    }
};

typedef std::result_of<decltype(Foo::foo)> foo_t;

But this doesn't work:

struct Foo
{
    static auto foo(int bar)
    {
        return 0;
    }

    typedef std::result_of<decltype(Foo::foo)> foo_t;
};

GCC says "error: use of 'static auto Foo::foo(int)' before deduction of 'auto'", Clang says "function 'foo' with deduced return type cannot be used before it is defined". Why?

Tangle answered 25/1, 2017 at 3:37 Comment(3)
I think you wanted to write std::result_of<decltype(&foo)(int)>::type isn't it?Honebein
@O'Neil There's a fair chance, I have visibly no idea how that works...Tangle
This is the subject of CWG2335.Angry
A
16

While the way you have written the code makes it appear possible, the in-class definition of foo() can only be processed after the class is fully defined. It is as if you wrote this:

struct Foo
{
    static auto foo(int bar);

    typedef std::result_of<decltype(Foo::foo)> foo_t;
};

auto Foo::foo(int bar)
{
    return 0;
}

The definition of foo() is allowed to use types defined in class Foo, including foo_t, which would be circular. Therefore, the definition of class Foo is not allowed to use the definition of its member functions--only their declarations.

In other words, you assume the code is fully evaluated from the top to the bottom. It is not.

Astro answered 25/1, 2017 at 4:0 Comment(1)
This is correct for all I know, but "you assume the code is fully evaluated from the top to the bottom" is a bit of an unfair statement.Tangle

© 2022 - 2024 — McMap. All rights reserved.