What are 'constexpr' useful for?

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

    Answer of " Can someone give me some insight why constexpr keyword was being introduced?"

    Modern C++ supports two types of immutability.

    1) const

    2) constexpr.

    constexper will be evaluated at the compile time. It is used to specify constness and allows placement of data in the memory where it might be corrupted.

    Example 1:

    void UseConstExpr(int temp)
    {
        // This code snippet is OK
        constexpr int y = max + 300;
        std::cout << y << std::endl;
        // This code snippet gives compilation error
        // [ expression must have a constant value]
        constexpr int z = temp + 300;
    
    }
    

    Example 2:

    int addVector(const std::vector& inVect)
    {
        int sum = 0;
        for ( auto& vec : inVect)
        {
            sum += vec;
        }
        std::cout << sum << std::endl;
        return sum;
    }
    
    int main()
    {
        // vInt is not constant
        std::vector vInt = { 1,2,3,4,5,6 }; 
        // This code snippet is OK
        // because evaluated at run time
        const int iResult = addVector(vInt);
        // Compiler throws below error
        // function call must have a constant value in a constant expression
        // because addVector(vInt) function is not a constant expression
        constexpr int iResult = addVector(vInt);
        return 0;
    }
    

    Note: above source code are compiled on VS2015

提交回复
热议问题