Can I make this a constexpr?

I have small array that I'm using to store some directional data. I'm trying to adapt this to be a member of a class:

1
2
3
4
5
6
7
8
9
10
11
12
class BVHTree {

    static constexpr Vector3 face_check_dirs[] = {
        Vector3(1, 0, 0),
        Vector3(-1, 0, 0),
        Vector3(0, 1, 0),
        Vector3(0, -1, 0),
        Vector3(0, 0, 1),
        Vector3(0, 0, -1)
    };

    ...


I'm getting an error saying that the expression must have a constant value. This is due to the Vector3 being mutable classes. When I try building a similar structure using primitive numbers, the syntax works.

I was wondering if there is a way to get this to work with a constexpr, or if I have to use const and keep my array in the .cpp file?

1
2
3
4
5
6
7
8
9

typedef float real;

struct Vector3 {
    real x;
    real y;
    real z;

    ...
The code below compiles OK with MS VS2022:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
typedef float real;

struct Vector3 {
	real x;
	real y;
	real z;
};

class BVHTree {
	static constexpr Vector3 face_check_dirs[] {
		Vector3(1, 0, 0),
		Vector3(-1, 0, 0),
		Vector3(0, 1, 0),
		Vector3(0, -1, 0),
		Vector3(0, 0, 1),
		Vector3(0, 0, -1)
	};
};

int main() {
	BVHTree t;
}

On GCC, it doesn't compile with -std=c++17, but will compile with -std=c++20 or beyond.

I believe the relevant change in the standard is explained here:
https://stackoverflow.com/a/76334358

(P0960R3, P1975R0) Aggregate initialization from a parenthesized list

Aggregates can now be initialized with round parentheses instead of curly braces: struct T { int a, b, c; }; T x(1, 2); A (motivating) consequence is that make_unique and emplace now work with aggregate types.
Last edited on
Registered users can post here. Sign in or register to post.