I've got the following code doing what I want in 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;
}
For the fixed integer value, it constructs my container silently and doubles the value, for the runtime integer value, it uses the verbose construction. The implementation allows me to declare fixed_container as constexpr.
I had to use c++20 for this to use the std::is_constant_evaluated feature, but I'm restricted to c++17. Is there some clever template magic I could employ to keep the same behavior without this feature?