如何在编译时检查使用ConstexPR构造函数的类实例是否会实例化?
如何检查myDouble
的实例将在编译时创建?
如果我用非恒定表达式实例化myDouble
会发生什么?
#include <iostream>
struct MyDouble{
double myVal;
constexpr MyDouble(double v): myVal(v){}
constexpr double getVal(){ return myVal; }
};
int main() {}
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() {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有标准方法可以在编译时间或运行时评估
constexpr
。您可以检查组件,遵循特定于实施的准则,也可以尝试推测。但是,使用C ++ 20,您可以强迫现有的
constexpr
在编译时评估,或者如果没有这种可能性,则会出现错误。相同的逻辑可以作为您的测试。进而:
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
constexpr
s 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.And then: