Skip to content

Instantly share code, notes, and snippets.

@schaumb
Last active May 17, 2023 10:56
Show Gist options
  • Save schaumb/1dec6415d9ae18e94195c03964a662e9 to your computer and use it in GitHub Desktop.
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
#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'
}
@schaumb
Copy link
Author

schaumb commented May 17, 2023

MSVC simple:

constexpr bool is_constant_evaluated() noexcept {
    struct M {
        int a;
    };
    struct N {
        int a;
    };
    struct C {};
    struct D1 : C, M {};
    struct D2 : C, N {};

    return static_cast<int D1::*>(&M::a) != 
        static_cast<int C::*>(static_cast<int D2::*>(&N::a));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment