4
#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 上编译:

error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘int’ in assignment
         x = std::string();

由于引用的行位于应该评估为 的 constexpr if 分支中false,所以程序不应该编译得很好吗?

4

1 回答 1

4

if constexpr规范定义了废弃的语句。然后它继续定义当实例化后结果不依赖于值时,丢弃的语句不实例化。这意味着在模板实例化期间语句被丢弃。此外,仅当条件值依赖于模板参数时,才会丢弃该语句。

于 2017-12-19T21:33:32.360 回答