7 Features of C++17 that will simplify your code

fenbf
598.1K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Inline variables

With Non-Static Data Member Initialization (see my post about it here), we can now declare and initialize member variables in one place. Still, with static variables (or const static) you usually need to define it in some cpp file.

C++11 and constexpr keyword allow you to declare and define static variables in one place, but it's limited to constexpr'essions only. I've even asked the question: c++ - What's the difference between static constexpr and static inline variables in C++17? - Stack Overflow - to make it a bit clear.

Ok, but what's the deal with this feature:

Previously only methods/functions could be specified as inline, but now you can do the same with variables, inside a header file.

A variable declared inline has the same semantics as a function declared inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is used, and the behavior of the program is as if there was exactly one variable.

struct MyClass
{
    static const int sValue;
};

inline int const MyClass::sValue = 777;

Or even:

struct MyClass
{
    inline static const int sValue = 777;
};

Also, note that constexpr variables are inline implicitly, so there's no need to use constexpr inline myVar = 10;.

Why can it simplify the code?

For example, a lot of header only libraries can limit the number of hacks (like using inline functions or templates) and just use inline variables.

The advantage over constexpr is that your initialization expression doesn't have to be constexpr.

More info in:

GCC: 7.0, Clang: 3.9, MSVC: in VS 2017.3.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content