Håkon Hægland
Håkon Hægland

Reputation: 40778

How to call a constexpr function from a preprocessor #if directive?

I want to define a macro as a string and later at compile time include code based on string comparison:

#include <iostream>
#include <string_view>

constexpr bool strings_equal(char const * a, char const * b) {
    return std::string_view(a)==b;
}

#define FOO "bar"


int main() {
#if strings_equal( FOO, "bar") == 0
    std::cout << "got a bar!" << '\n';
#endif
    return 0;
}

Compiling this with

$ g++ -std=c++17 test.cpp -o my_test

gives error:

test.cpp:12:18: error: missing binary operator before token "("
   12 | #if strings_equal( FOO, "bar") == 0
      |                  ^

Edit:

It appears that it matters if the #if directive is inside a function or not, since if it is inside a function we can replace it with if constexpr (...) { ... } But that is not possible if the #if is outside a function in the top level of a file.. and I forgot to mention that in my real code that is the case.

Upvotes: 1

Views: 717

Answers (1)

DevO
DevO

Reputation: 375

This is not possible to do this way.

But you can use if constexpr like this.

#include <iostream>
#include <string_view>

constexpr bool strings_equal(char const * a, char const * b) {
    return std::string_view(a)==b;
}

constexpr auto FOO = "bar";

int main() {
    if constexpr (strings_equal( FOO, "bar")) {
        std::cout << "got a bar!" << '\n';
    }

    return 0;
}

Run-able Code

Upvotes: 7

Related Questions