Непонятки с if constexpr

Следующий код нормально компилируется

#include <string>

void set(bool);

void set(std::string) {
}

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

но, если добавить ветку else

#include <string>

void set(bool);

void set(std::string) {
}

int main() {
    if constexpr (false) set(true);
    else set("");
}

то получается

undefined reference to `set(bool)'

https://godbolt.org/z/jirML9

буду благодарен тому, кто может объяснить, почему так происходит или ткнуть меня в правильное место стандарта.


Ответы (1 шт):

Автор решения: user7860670

set(""); в этом примере вызывает перегрузку void set(bool); Если заменить void set(std::string) на void set(char const *), то второй пример также будет нормально собираться:

8.5.1 The if statement [stmt.if]
2 If the if statement is of the form if constexpr , the value of the condition shall be a contextually converted constant expression of type bool (7.7); this form is called a constexpr if statement. If the value of the converted condition is false , the first substatement is a discarded statement, otherwise the second substatement, if present, is a discarded statement. During the instantiation of an enclosing templated entity (13.1), if the condition is not value-dependent after its instantiation, the discarded substatement (if any) is not instantiated. [Note: Odr-uses (6.3) in a discarded statement do not require an entity to be defined. —end note]

→ Ссылка