How to emulate std::is_constant_evaluated in c++17?

Viewed 193

I've got the following code doing what I want in c++20:

#include <iostream>

struct IntContainer
{
    int value;
    
    constexpr IntContainer(int init):value(init)
    {
        if(std::is_constant_evaluated())
        {
            value*=2;
        }
        else
        {
            std::cout<<"Constructed at runtime"<<std::endl;
        }
    }
};

int main()
{
    constexpr int fixed=99;
    int runtime;
    std::cout<<"Enter runtime int value"<<std::endl;
    std::cin>>runtime;
    
    constexpr IntContainer fixed_container(fixed);
    IntContainer runtime_container(runtime);
    return 0;
}

For the fixed integer value, it constructs my container silently and doubles the value, for the runtime integer value, it uses the verbose construction. The implementation allows me to declare fixed_container as constexpr.

I had to use c++20 for this to use the std::is_constant_evaluated feature, but I'm restricted to c++17. Is there some clever template magic I could employ to keep the same behavior without this feature?

1 Answers

Which compiler are you using? While std::is_constant_evaluated is only available since C++20, compilers often have extension function like that to determine better algorithms in their library.

For instance, GCC uses __builtin_constant_p prior to is_constant_evaluated.

Demo: GCC 6.1 running C++17

Related