2

Consider this non-templated class

struct Foo {
    constexpr static bool TRUE() {
        return true;
    }
};

Calling Foo::TRUE() from outside works fine:

int main() {
    static_assert(Foo::TRUE(), "");
}

but not when called from Foo itself:

struct Foo {
    constexpr static bool TRUE() {
        return true;
    }
    static_assert(Foo::TRUE(), ""); //ERROR
};

Error (active) E0028 expression must have a constant value
Error C2131 expression did not evaluate to a constant

Even weirder is that this can be "fixed" by providing the class a template:

template<int x>
struct Foo {
    constexpr static bool TRUE() {
        return true;
    }
    static_assert(Foo::TRUE(), ""); //compiles fine
};

int main() {
}

Even though Foo::TRUE() has nothing to do with int x.


What's going on?


I am using Visual Studio 17 Community Version 15.9.0 - thanks for any help

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
  • Gcc gives [a somewhat better error message](https://coliru.stacked-crooked.com/a/6c98acd61d66ec6d). – nwp Dec 05 '18 at 13:24
  • @nwp so how can you make it fully visible? – Stack Danny Dec 05 '18 at 13:26
  • What do you mean by "make it visible"? As far as I can tell the problem is that there is a circular definition. The `static_assert` depends on if `Foo::TRUE()` is `true` which depends on the `static_assert`. – nwp Dec 05 '18 at 13:28
  • What if you put the static_assert in the constructor of the struct? – jwimberley Dec 05 '18 at 13:29
  • I expect this to be a 2 pass compilation issue. The compiler runs through the entire class body once before it compiles the body of member functions/static functions. So at the time static_assert is reached, the function TRUE is still considered to not be fully defined which is why it returns an error – MS Srikkanth Dec 05 '18 at 13:33
  • @jwimberley that works, thanks. Though I am still confused about how the template avoids the circulation. – Stack Danny Dec 05 '18 at 13:35
  • [CWG 1626](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1626) – cpplearner Dec 05 '18 at 14:10

0 Answers0