As we have seen constexpr functions which maybe evaluated at compile time or runtime, aggregates can also be constexpr. To use struct in constexpr contexts, we need to:

  1. Declare the struct variable using constexpr
  2. If the member function is called in constexpr contexts, it has to be declared constexpr (if you are defining function outside, the constexpr should be with the declaration inside the struct definition).

For example,

#include <iostream>
 
struct Point
{
    int x;
    int y;
 
    constexpr int greaterCoordinate() const
    {
        return x < y ? y : x;
    }
};
 
void printPoint(Point p)
{
    std::cout << "{" << p.x << ", " << p.y << "}\n";
}
 
int main(int argc, char const *argv[])
{
    constexpr Point p{1, 2};
 
    std::cout << "Greater coordinate: " << p.greaterCoordinate() << "\n";
    
    constexpr int greater{p.greaterCoordinate()};
    std::cout << "Greater coordinate: " << greater << "\n";
    return 0;
}

The first p.greatCoordinate() maybe evaluated at compile time or run time as it is used in non-constexpr context. The second call will be evaluated at compile time as it is called constexpr context.

Tip

Aggregates implicitly supports constexpr and so declaring struct with constexpr works without any issues.

References

  1. https://www.learncpp.com/cpp-tutorial/constexpr-aggregates-and-classes/