7

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

#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 ответ 1

8

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]

3
  • Кусок стандарта совершенно не тот. Вроде он про условие if'а.
    – Qwertiy
    12 июн 2020 в 21:12
  • @Qwertiy If the if statement is of the form if constexpr, а потом про каждый из двух substatement. Потом там еще и пример соотв. приведен, демонстрирующий что ODR использование в отбрасываемом выражении не требует, чтобы сущность была определена. 12 июн 2020 в 21:14
  • Или же вызвать set(string("")) 13 июн 2020 в 8:42

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.