如何在编译时检查使用ConstexPR构造函数的类实例是否会实例化?

发布于 2025-01-28 13:24:08 字数 292 浏览 3 评论 0原文

如何检查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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

依 靠 2025-02-04 13:24:08

没有标准方法可以在编译时间或运行时评估constexpr。您可以检查组件,遵循特定于实施的准则,也可以尝试推测。

但是,使用C ++ 20,您可以强迫现有的constexpr在编译时评估,或者如果没有这种可能性,则会出现错误。相同的逻辑可以作为您的测试。

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

进而:

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

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

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));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文