[ Web Proxy ]
URL:
Viewing: https://ru.cppreference.com/cpp/types/is_constant_evaluated [Back]  [Original]

std::is_constant_evaluated cppreference.com
cppreference.com

std::is_constant_evaluated

cppreference.com
<tbody> </tbody>
constexpr bool is_constant_evaluated() noexcept;
( C++20)

, . true, , ; false.

, , :

  • const- ;

.

int y = 0;
const int a = std::is_constant_evaluated() ? y : 1;
//     .   .
//  a   1

const int b = std::is_constant_evaluated() ? 2 : y;
//   std::is_constant_evaluated() == true  .
//  b    2

()

true, , ; false.

//    C++23,  consteval.
constexpr bool is_constant_evaluated() noexcept
{
    if consteval
    {
        return true;
    }
    else 
    {
        return false;
    }
}

static_assert constexpr if, std::is_constant_evaluated() true.

if consteval C++20, std::is_constant_evaluated .

__cpp_lib_is_constant_evaluated 201811L (C++20) std::is_constant_evaluated

#include <cmath>
#include <iostream>
#include <type_traits>

constexpr double power(double b, int x)
{
    if (std::is_constant_evaluated() && !(b == 0.0 && x < 0))
    {
        //   :  ,   constexpr.
        if (x == 0)
            return 1.0;
        double r {1.0};
        double p {x > 0 ? b : 1.0 / b};
        for (auto u = unsigned(x > 0 ? x : -x); u != 0; u /= 2)
        {
            if (u & 1)
                r *= p;
            p *= p;
        }
        return r;
    }
    else
    {
        //    .
        return std::pow(b, double(x));
    }
}

int main()
{
    //   
    constexpr double kilo = power(10.0, 3);
    int n = 3;
    //   ,   n   
    //      
    //  std::pow(10.0, double(n))
    double mucho = power(10.0, n);

    std::cout << kilo << " " << mucho << "\n"; // (3)
}

:

1000 1000

constexpr(C++11) , []
consteval (C++20) , , []
constinit (C++20) , , []

Web Proxy Viewer  |  New URL  |  Original Page