I have a Vec
struct that represents a 3D vector, and I want to make it's static member Zero
constexpr.
struct Vec
{
double X;
double Y;
double Z;
static const Vec Zero; // defined in it's own .cpp file
// ... some functions and operators
};
I tried the following approach, but this code fails to compile with incomplete type is not allowed
.
struct Vec
{
double X;
double Y;
double Z;
static constexpr Vec Zero{ 0.0, 0.0, 0.0 };
};
Then I tried to move the definition out of the struct. This compiles, but fails in linking phase, with duplicate symbol Vec::Zero
error. (Vec
is in the .h file that is included by many .cpp files)
struct Vec
{
double X;
double Y;
double Z;
static const Vec Zero;
};
constexpr Vec Vec::Zero{ 0.0, 0.0, 0.0 }; // this definition is in .h file, not in .cpp
What is the proper way to make Vec::Zero
constexpr? Is it possible at all?
EDIT:
As pointed out by @Artyer, since C++17 inline
can be used to solve the problem. The following code works:
struct Vec
{
double X;
double Y;
double Z;
static const Vec Zero;
};
inline constexpr Vec Vec::Zero{ 0.0, 0.0, 0.0 }; // this definition is in .h file, not in .cpp