What are 'constexpr' useful for?

前端 未结 4 524
说谎
说谎 2021-02-04 06:07

I really can\'t find any use of it. My first idea was that I could use it to implement \'Design by Contract\' without using macros like this:

struct S
{   
    S         


        
4条回答
  •  执念已碎
    2021-02-04 06:31

    The way I see it, constexpr is a way to bring together the two C++ languages - the one that runs at runtime and the one that runs at compile time. Compile time programming is usually called meta-programming.

    First there was C, with its macros. Macros were in fact little programs that were ran by the compiler. They had if statements (called #ifdef), variables (with #define). There's even an entire scripting language that runs in compile time.

    When C++ came out, it had the C macros and nothing more. Then came the C++ templates. These introduced a different way of running compile-time code. The C++ meta-language was largely functional, allowing you to do loops with tail recursion, for example.

    In C++ 11, they've decided that meta-programming can look better, so they've introduced constexpr. Now you can write C++ functions that are also meta-functions. In C++ 14 it gets better, because the restrictions on constexpr functions have been relaxed.

提交回复
热议问题