jon*_*lpy 5 c++ constexpr c++17
我有以下代码在 c++20 中执行我想要的操作:
#include <iostream>
struct IntContainer
{
int value;
constexpr IntContainer(int init):value(init)
{
if(std::is_constant_evaluated())
{
value*=2;
}
else
{
std::cout<<"Constructed at runtime"<<std::endl;
}
}
};
int main()
{
constexpr int fixed=99;
int runtime;
std::cout<<"Enter runtime int value"<<std::endl;
std::cin>>runtime;
constexpr IntContainer fixed_container(fixed);
IntContainer runtime_container(runtime);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于fixed整数值,它默默地构造我的容器并将该值加倍,对于整runtime数值,它使用详细构造。该实现允许我声明fixed_container为constexpr.
我必须使用 c++20 才能使用该std::is_constant_evaluated功能,但我仅限于 c++17。是否有一些聪明的模板魔法我可以用来在没有此功能的情况下保持相同的行为?
您使用哪个编译器?虽然std::is_constant_evaluated仅从 C++20 起可用,但编译器通常具有类似的扩展函数来确定其库中更好的算法。
例如,GCC 使用__builtin_constant_pbefore is_constant_evaluated.