CPP in Practice - Developer's Blog

CPP in Practice - Developer's Blog

Share

17/02/2021

✅Values known during compilation are privileged, right? The keyword constexpr was introduced in C++11 and improved in C++14 which allows to define an expression that can be evaluated at compile time. They may be placed in read-only memory.

📌All constexpr objects are const, but not all const objects are constexpr. This is because const object’s value may be not known at compilation.

int i;

const auto k = i; /// OK
constexpr int m = 0; /// OK
constexpr int n = i; /// Error

✅constexpr is part of an object’s or function’s interface. In case when we have objects whose values are known during compilation we can define functions as constexpr too.

Small example:

constexpr int max_count()
{
return 100;
}

✅constexpr functions are limited to taking and returning literal types, which essentially means types that can have values determined during compilation. The user-defined types also can be literal, too, because we can declare constructors and member functions as constexpr.

class Pair
{
public:
constexpr Pair(double f = 0.0, double s = 0.0) noexcept
: first(f), second(s) {}

constexpr double get_first() const noexcept { return first; }
constexpr double get_second() const noexcept { return second; }

void set_first(double f) noexcept { first = f; }
void set_second(double s) noexcept { second = s; }
private:
double first;
double second;
};

✅In this case we can create an object of Pair type as constexpr.

constexpr Pair p1(1.0, -1.0); /// OK
Pair p2; /// OK

✅Now, when we have constexpr getter functions in Pair, we can use them inside of constexpr functions. Example:

constexpr bool less(const Pair& p1, const Pair& p2) noexcept
{
if (p1.get_first() < p2.get_first()) {
return true;
} else if (p1.get_first() == p2.get_first()) {
return p1.get_second() < p2.get_second();
}
return false;
}

less(p1, p2); /// OK, because values of p2 are known during compilation

✅So, both constexpr objects and constexpr functions can be employed in a wider range of contexts than non-constexpr objects and functions. This is why declaration constexpr objects and functions preferred whenever it is possible.

📚Read more about constexpr specifier - https://en.cppreference.com/w/cpp/language/constexpr
📚constexpr keyword usage and advices - Scott Meyers, Effective Modern C++, Item 15: Use constexpr whenever possible

Want your school to be the top-listed School/college in Yerevan?
Click here to claim your Sponsored Listing.

Category

Website

Address


Yerevan