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:
- Declare the struct variable using
constexpr - If the member function is called in constexpr contexts, it has to be declared
constexpr(if you are defining function outside, theconstexprshould 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
constexprand so declaring struct withconstexprworks without any issues.