Last active
May 17, 2023 10:56
-
-
Save schaumb/1dec6415d9ae18e94195c03964a662e9 to your computer and use it in GitHub Desktop.
>=gcc6.1 and >=c++11 is_constant_evaluated() function implementation with manual memory setting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <type_traits> | |
namespace { | |
unsigned char v{}; | |
constexpr bool is_constant_evaluated(const unsigned char* e = &v) { | |
return e - 0x6017d2; // memory dependent constant value, check output first line | |
} | |
} | |
constexpr int test() { | |
return is_constant_evaluated() ? 45 : ((std::cout << "[noconstexpr call] "), 20); | |
} | |
int main() { | |
std::cout << (const void*) &v << std::endl; // set is_constant_evaluated constant number to this memory address | |
constexpr bool cexpr = is_constant_evaluated(); | |
std::cout << cexpr << " " << is_constant_evaluated() << std::endl; // '1 0' | |
constexpr int t = test(); | |
std::cout << t << " and " << test() << std::endl; // '[noconstexpr call] 45 and 20' or '45 and [noconstexpr call] 20' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MSVC simple: