template<typename T>
T f() {
if constexpr (std::is_same<T, int>::value) {
T t = 10;
}else {
T t;
}
return t;
}
My understanding of the above code is that the body of f
will either be
int t = 10;
return t;
or
T t = // some default value for T
return t;
depending on T
. In both there will be an identifier called t
. Why does the compiler still complain about use of undeclared identifier 't'
?.
Does the compiler check for undeclared identifiers before it resolves constexpr
statements?
My understanding of the above code is that the body of f will either be
int t = 10; return t;
or
T t = // some default value for T return t;
No. A more valid comparison is that it will be either, for the true
branch:
{
int t = 10;
} // end of scope for 't'
return t; //
or, for the else
branch:
{
T t;
} // end of scope for 't'
return t;
Meaning the t
in the return statement refers to an entity that does not exist (in that scope).