What are 'constexpr' useful for?

前端 未结 4 514
说谎
说谎 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:36

    Here is a summary of points made by Alex Allain in his "Constexpr - Generalized Constant Expressions in C++11," which details the usefulness of constexpr:

    • First, with a constexpr specifier, the value of the function or variable can be at compile time.
    • Another benefit of the constexpr specifier is that it can replace macros with functions
    • constexpr will also benefit your template metaprogramming.

    Benefit to efficiency:

    constant expressions...allow certain computations to take place at compile time, literally while your code compiles rather than when the program itself is run. (Allain 2)

    Performance benefit: if something can be done at compile time, it will be done once, rather than every time the program runs

    Other benefits:

    Such variables and functions can then be used where only compile time constant expressions are allowed. A constexpr specifier used in an object declaration implies const. A constexpr specifier used in an function declaration implies inline.(CPP 1)

    Rules for constexpr functions:

    1. It must consist of single return statement (with a few exceptions)
    2. It can call only other constexpr functions
    3. It can reference only constexpr global variables (Allain 6)

    Rules for constexpr constructors:

    1. each of its parameters must be literal type
    2. the class must have no virtual base classes
    3. the constructor must not have a function-try-block (CPP 6)

    Citations

    Allain, Alex, "Constexpr - Generalized Constant Expressions in C++11", Unspecified Date, "http://www.cprogramming.com/c++11/c++11-compile-time-processing-with-constexpr.html"

    CPP, "Constexpr Specifier", 16 December 2014, http://en.cppreference.com/w/cpp/language/constexpr


    EDIT: Sorry, It was my fault to make it seem like I was the author of these points, so I have corrected myself, changed various parts, and added citations to avoid plagiarism.

提交回复
热议问题