How to check if instances of a class with a constexpr constructor get instantiated at compile time?

145 views Asked by At

How can I check that instances of MyDouble will be created at compile time?

What will happen if I instantiate MyDouble with a non-constant expression?

#include <iostream>

struct MyDouble{
    double myVal;
    constexpr MyDouble(double v): myVal(v){}
    constexpr double getVal(){ return myVal; }
};

int main() {}
1

There are 1 answers

0
sorush-r On

There is no standard way to determine if a constexpr will be evaluated at compile-time or run-time. You can either inspect the assembly, follow the implementation-specific guidelines or try to speculate.

However, using C++20 you can force your existing constexprs to be evaluated at compile-time, or get an error if there is no such possibility. The same logic can act as a test for you.

template<class T>
consteval T compile(T exec) 
{
    return exec;
}

And then:

struct MyDouble
{
    double myVal;
    constexpr MyDouble(double v): myVal(v){}
    constexpr double getVal(){ return myVal; }
};

int main() 
{
    MyDouble x = compile(MyDouble(3.14));
}