问题
#include <iostream>
int foo(int x) {
if constexpr (std::is_same_v<decltype(x), std::string>) {
x = std::string();
}
}
int main(void)
{ return 0; }
This code doesn't compile on either GCC 7 nor Clang 5:
error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘int’ in assignment
x = std::string();
Since the referenced line is in a constexpr if branch that should evaluate to false
, shouldn't the program compile fine?
回答1:
The if constexpr
specification defines the discarded statement. It then goes on to define that the discarded statement is not instantiated when the result is not value-dependent after instantiation. The implication is that statements are discarded during template instantiation. Further, the statement is only discarded if the conditional value is dependent on the template arguments.
来源:https://stackoverflow.com/questions/47895308/constexpr-if-with-non-template-types