Using constexpr if instead of macros when writing platform-specific code?

Now that it if constexpris part of C ++ 17, is it a good replacement for macros when writing platform-specific code and the like?

I am interested because I really do not like macros, and I would like to use them only to turn on and off guards.

// those variables should be given by the compiler
constexpr unsigned int __os = 0x1; // current os
constexpr unsigned int __os_win = 0x1; // Windows
constexpr unsigned int __os_linux = 0x2; // Linux-flavors
constexpr unsigned int __os_apple = 0x4; // Mac os

void print_os() {
    if constexpr (__os == __os_win)
        std::cout << "You're on Windows!\n";
    else if constexpr (__os == __os_linux)
        std::cout << "You're on a Linux OS!\n";
    else if constexpr (__os == __os_apple)
        std::cout << "You're on Mac OS!\n";
}

instead of the current solution:

void print_os() {
#ifdef _WIN32
    std::cout << "You're on Windows!\n";
#elif __linux__
    std::cout << "You're on a Linux OS!\n";
#elif __APPLE__
    std::cout << "You're on Mac OS!\n";
}

Both methods will not generate code for other platforms when compiling, so they are technically the same, and I would prefer the path constexpr(if possible).

constexpr ? - gcc, clang, , . ?

+4
2

, , . . , , , , .

Python asyncio , async await , @coroutine . .

, . os, constexpr. , , , . 2 . , .

+1

, C ifdefs . , . Constexpr , , , .

-1

Source: https://habr.com/ru/post/1671447/


All Articles