I'm trying to compile this code, but g++ complains about ZERO
having an incomplete type. Does this mean that in C++ a struct cannot contain a static constexpr
instance of itself? If so, why?
struct Cursor
{
size_t row,column;
static constexpr Cursor ZERO {0,0};
//error: constexpr const Cursor Cursor::ZERO has incomplete type
};
EDIT: I understand that Cursor
cannot have a complete type when I declare ZERO
. What I'd like to know is: is there any way I can have ZERO
belonging to Cursor
and still being constexpr
?
Yes, if you count nested subclasses as "belonging to" the containing class:
Unfortunately, you simply cannot do this!
Some
static constexpr
members may be initialised inline:Cursor
is a literal type, so this counts.And the use of
Cursor
itself as astatic
data member within its own type is not a problem, as long as you initialise it at lexical namespace scope:But you can't do that with
constexpr
:I think all of this wording could be improved but, in the meantime, I think you're going to have to make
ZERO
a non-member in the enclosing namespace.This answer to a similar question revealed that this is, in fact, possible to accomplish. You just have to put the
constexpr
keyword with the definition rather than the declaration:Fully tested with GCC (ideone), clang (rextester), and MSVC++ 2017 (note that IntelliSense doesn't like it, but it compiles correctly!).
You can if you accept to have a function, not a variable