I wanted to wrap both constexpr and non-constexpr behaviour inside a function and that seems possible (ref : calling non constexpr function from constexpr allowed in some conditions)
Following shows same snippet:
void bla( )
{
std::cout << "bla called!" << std::endl;
}
constexpr bool check(bool condition)
{
//bla(); // can not directly be called -> not constexpr!
condition ? void (0) : bla(); // compiles and runs even if condition is true or false!
true ? void(0): bla(); // also that compiles!, ok, directly evaluated
false ? bla(): void(0); // compiles, ok, directly evaluated
return 0;
}
int main()
{
check( false );
check( true );
}
So check(false)
works and I am able to call bla()
(a non-constexpr function) from constexpr function as expected (reasong being given in the ans in the link).
My usecase is I want to use this constexpr function inside if constexpr.. and that fails:
void bla( )
{
std::cout << "bla called!" << std::endl;
}
constexpr bool check(bool condition)
{
//bla(); // can not directly be called -> not constexpr!
condition ? void (0) : bla(); // compiles and runs even if condition is true or false!
true ? void(0): bla(); // also that compiles!, ok, directly evaluated
false ? bla(): void(0); // compiles, ok, directly evaluated
return 0;
}
int main()
{
if constexpr(check( false )){}; // throws compiler error
if constexpr(check( true )){};
}
above snippet: https://godbolt.org/z/4c5PvEhcb
Is it possible to call if constexpr on above function? My use-case in general is: I want to have two version of a function depending upon build flags but both are called from if constexpr to keep rest of the code clean. Minimal example:
#include <iostream>
#define SIMULATION
size_t get_count() { return 10; }
#if defined(SIMULATION)
inline constexpr bool func(bool compile_time_flag = false) // compile_time_flag param added so that one of the evaluation of the function is constexpr (when flag = true)
{
bool ret_val = false;
ret_val = compile_time_flag ? false : (get_count() > 1);
return ret_val;
}
#else
inline constexpr bool func(bool compile_time_flag = true)
{
return false;
};
#endif
//somewhere in code
int main()
{
if constexpr(func())
{
std::cout << " It works! ";
}
return 0;
}
above snippet: https://godbolt.org/z/4KhcabPqn. Doesn't work when SIMULATION is defined.
Is it possible what I am trying to do? I don't want to wrap the whole usage of constexpr(func())
vs (func())
depending upon build flag (looks ugly):
#if define SIMULATION
# define CHECK_COND (func())
#else
# define CHECK_COND constexpr(func())
int main()
{
if CHECK_COND
{
std::cout << " It works! ";
}
return 0;
}
Dont want to do above, which should work.
Is there a better way to acheive the same? Thanks!