GAMERZNIGHTMARE
GAMERZNIGHTMARE

Reputation: 21

Constexpr / Compile time constant expressions bugs

I get the following error in my project upon compiling. Tried everything but unable to resolve this.

Reproduced the error here: https://replit.com/join/egfoiwpgig-darshanpandhi

Error

error: constexpr variable 'noOfTiles' must be initialized by a constant expression

Relevant Code

Board.h

# pragma once

class Board {
private:

public:
    static constexpr int getTotalNoOfTiles();
};

Board.cpp

# include "Board.h"


constexpr int Board::getTotalNoOfTiles() {
    return 21;  // calculation simplified for the sake of example
}

Player.h

# pragma once

# include "Board.h"


class Player {
private:
    static constexpr int noOfTiles = Board::getTotalNoOfTiles();   // this needs to be constexpr because I will be using noOfTiles as an array size in this same file
};


Question

Isn't Board::getTotalNoOfTiles() a constant expression since it simply returns 21. Isn't this a compile-time constant?

Reproduced the error here: https://replit.com/join/egfoiwpgig-darshanpandhi

Upvotes: 1

Views: 80

Answers (1)

user17732522
user17732522

Reputation: 76829

The definition of a constexpr function, just like a inline function which it implies, belongs into the header, not in a .cpp file, at least if it is supposed to be used in other translation units.

In this case, either define it directly in the class definition or put the definition after the class definition in the header file.

Without that the definition of the function would also not be visible to the compiler when compiling the call in the other translation unit, so it couldn't possibly make use of it at compile-time, i.e. in a constant expression.

Upvotes: 3

Related Questions