2

The following code

#include <string>

void set_string(std::string) {
}

int main() {
    if constexpr (false) {set_string(true);}
}

does not compile with an error

error: no matching function for call to 'set_string'

        if constexpr (false) {set_string(true);}

                              ^~~~~~~~~~

<source>:3:6: note: candidate function not viable: no known conversion from 'bool' to 'std::string' (aka 'basic_string<char>') for 1st argument

But set_string(true) is discarded statement and should be dropped. I'm right?

tilin
  • 332
  • 1
  • 7
  • 2
    Usually the condition must depend on some template parameter. I'd look for a dup, but I'm on mobile – AndyG Jun 12 '20 at 20:49
  • 2
    If you really think about it, there is no reason to have `if constexpr (false)`. You know, right then and there that the branch will never be called, so you can just not write it. It's when you get into templates, where the compiler has to deduce the value of the condition, where constexpr if makes sense. – NathanOliver Jun 12 '20 at 20:53
  • Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive. – andrès coronado Jun 12 '20 at 21:04
  • @NathanOliver: One possible reason might be to replace some pre-processor condition. To have something like `if constexpr (Windows)` instead of `#ifdef __WIN32`. – Jarod42 Jun 12 '20 at 21:11
  • @Jarod42 That wasn't what it was designed for though. We already have have the preprocessor. What we did not have was an easy way to do different things based on the different types passed to a template function. – NathanOliver Jun 12 '20 at 21:15
  • @NathanOliver: Some people expect to get rid of MACRO and pre-processor stuff with future of C++. ((variadic) template, `constexpr`, `std::source_location`, ..., go in that direction (even if it was not necessary their primary goal)). – Jarod42 Jun 12 '20 at 21:22
  • And without that, there are still stuff to handle implementation specific stuff as `if constexpr (sizeof (int) == 4)`. – Jarod42 Jun 13 '20 at 18:47

0 Answers0