'How to check if instances of a class with a constexpr constructor get instantiated at compile time?
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() {}
Solution 1:[1]
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));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sorush-r |
