lundi 20 septembre 2021

What is the behavior of the compiler in if constexpr statement, C++?

In the section about selection statements in C++ ISO, there is no much information, particularly it says:

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

In Cppreference we have:

If a constexpr if statement appears inside a templated entity, and if condition is not value-dependent after instantiation, the discarded statement is not instantiated when the enclosing template is instantiated ... Outside a template, a discarded statement is fully checked.

There is more information in Difference between "if constexpr()" Vs "if()". But through this post I understood that discarded statements were never compiled, at least in templates, but my code below is checked and compiled, I am using Visual Studio 2019, C++20.

#include <iostream>
using namespace std;
template<typename T>
void whatever(T value){
    if constexpr (true) {
        cout<<value<<endl;
    }
    else {
        cout << never be compiled? << endl; //conscious error
    }
}
int main() {
    whatever<int>(2);
}

Maybe Im missing a more rigorous definition of instantiation / compilation / discarded. What happens in "discarded statements" in if constexpr?

Aucun commentaire:

Enregistrer un commentaire