问题描述
#include <iostream>
int foo(int x) {
if constexpr (std::is_same_v<decltype(x), std::string>) {
x = std::string();
}
}
int main(void)
{ return 0; }
此代码无法在GCC 7或Clang 5上编译:
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();
由于引用的行在constexpr中(如果分支的求值应为false
),程序是否应该编译正常?
Since the referenced line is in a constexpr if branch that should evaluate to false
, shouldn't the program compile fine?
推荐答案
if constexpr
规范定义了废弃的语句.然后,它继续定义当结果不依赖于实例化后的 时,不实例化被丢弃的语句.暗示是语句在模板实例化期间被丢弃.此外,仅在条件值取决于模板参数的情况下才丢弃该语句.
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.
这篇关于如果使用非模板类型,则为Constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!