0

I want to get rid of most #ifdef-clauses if possible. To that end, my code would contain many cases of the following pattern:

template<bool b>
void f(){
    if constexpr (b) {
        invalid;
    }
}

to replace code of the form

void f(){
    #ifdef FOO
    code_invalid_unless_FOO_is_defined;
    #endif
}

The first example not compile, as invalid_code is not declared.

I had hoped that everything inside if constexpr is ignored, which seems to be not the case. Can I use if constexpr at all to eliminate preprocessor usage of that form?

Edit: this question is different from the linked one, because it involves templates. The statements on this site made me think that in that case, the code inside a discarded constexpr is not checked.

Bubaya
  • 615
  • 3
  • 13
  • 4
    if constexpr only works when the condition depends on a template parameter. – NathanOliver Oct 17 '22 at 17:45
  • 2
    _"...Outside a template, a discarded statement is fully checked. `if constexpr` is __not__ a substitute for the `#if` preprocessing directive:..."_ https://en.cppreference.com/w/cpp/language/if#Constexpr_if – Richard Critten Oct 17 '22 at 17:48
  • It's summarised pretty succinctly [here](https://stackoverflow.com/a/46512580/817643). – StoryTeller - Unslander Monica Oct 17 '22 at 17:48
  • 1
    If "everything" inside `if constexpr` was ignored, how would the compiler determine where the `if constexpr` ends? – Daniel McLaury Oct 17 '22 at 17:49
  • 1
    There's nothing wrong with the style of the second code snippet. Why do you want to rewrite it? (Note that I'm asking an engineering question; "ugh, preprocessor bad" is not an engineering answer) – Pete Becker Oct 17 '22 at 17:49
  • 2
    Does this answer your question? [#if Vs if constexpr](https://stackoverflow.com/questions/71797365/if-vs-if-constexpr) – ChrisMM Oct 17 '22 at 17:55
  • @RichardCritten That's a good hint. However, it also does not work in templates, as the updated question shows. – Bubaya Oct 17 '22 at 18:07
  • It's not like you can opt of of preprocessor completely, what with RTL headers being what they are. – Seva Alekseyev Oct 17 '22 at 18:12

0 Answers0