1

As far as I read the following code is C++17 compliant, and indeed clang > 5.0 accepts it, but not gcc 8.2.

#include <type_traits> // for is_literal_type_v

struct Wrapper
{
    constexpr Wrapper() :
        initialised_(false),
        value_(0)
    {
    }
    constexpr Wrapper(int value) :
        initialised_(true),
        value_(value)
    {
    }
    const bool initialised_;
    const int value_;
};

static_assert(std::is_literal_type_v<Wrapper>, "must be a literal type");


struct Container
{
    static constexpr Wrapper w; // error: 'constexpr' static data member 'w' must have an initializer
};


int main()
{
}

This is discussed in this question, but on top of that I'd like to ask if there is any way (other than, well, providing an initializer) to make it work. What I'd like to achieve is to have the no-arg c-tor of Wrapper called in this case (of course).

Additionally, it would be good to identify the GCC bug if there is one.


Edit: To note, my current workaround is to use namespace instead of struct. At namespace scope the constexpr doesn't require an initializer, it seems. But this reduces flexibility of something I'm doing.

haelix
  • 4,245
  • 4
  • 34
  • 56

1 Answers1

0

Use list initialization syntax (curly braces):

struct Container
{
    static constexpr Wrapper w{};
};
Oz Solomon
  • 2,969
  • 23
  • 22
  • sure, but this is not a workaround for me as I need something to work in a very generic context (a macro to be precise), where passed items might or might not have initialisers – haelix Jan 18 '19 at 20:58
  • A more complete example of what you're trying to do would be useful. – Oz Solomon Jan 20 '19 at 23:10