我的代码如何在编译时做一件事,而在运行时做另一件事? [英] How can my code do one thing at compile-time, but another thing at run-time?

查看:52
本文介绍了我的代码如何在编译时做一件事,而在运行时做另一件事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现 constexpr int foo(); 函数.在 foo()的正文中,我想在编译时做一些不同的事情(并可能返回不同的东西),而在运行时做一些不同的事情.

对于C ++ 20,我可以使用 std :: is_constant_evaluated :

  constexpr int foo(){return std :: is_constant_evaluated()?123:456}; 

但是,如果我使用的是C ++ 17(或更早版本),该怎么办?我该怎么做才能达到相同的效果?

注意:编译器特定的解决方案是可以接受的(尽管较不理想).

解决方案

注意:编译器特定的解决方案是可以接受的(尽管较不理想).

让我们提及最明显的例子:

clang-9 .

I'm implementing a constexpr int foo(); function. In the body of foo(), I want to do something different (and possibly return something different) at compile time and something different at run-time.

With C++20, I can use std::is_constant_evaluated:

constexpr int foo() { return std::is_constant_evaluated() ? 123 : 456 };

but what if I'm using C++17 (or earlier) - what can I do with the same effect?

Note: Compiler-specific solutions are acceptable (though less desirable).

解决方案

Note: Compiler-specific solutions are acceptable (though less desirable).

Let's mention the most obvious ones:

gcc has __builtin_is_constant_evaluated() at least documented since 9.2.0.

clang has the same builtin since clang-9.

这篇关于我的代码如何在编译时做一件事,而在运行时做另一件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆