Search code examples
c++c++14constexprinner-classes

Is it possible to have static constexpr fields in a private inner class?


I have a C++14 project and cannot use C++17 inline variables.

// myclass.h
class MyClass {
  struct Inner {
    using StringArray = std::array<const char*, 1>;
    static constexpr StringArray kStrings{{ "foo" }};
  }
}

//myclass.cpp
constexpr MyClass::Inner::StringArray kStrings;
//                 ^^^^^                   
// Error: "Inner" is a private member of "MyClass"

Is it possible to get this to work in C++14, or will this only work in C++17?


Solution

  • Your trying to give a definition for a new file-scope variable called ::kStrings. You want to define the static member MyClass::Inner::kStrings instead:

    constexpr MyClass::Inner::StringArray MyClass::Inner::kStrings;