Constexpr是否包含非模板类型

时间:2017-12-19 21:17:17

标签: c++ c++17 if-constexpr

#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,所以程序编译不应该正常吗?

1 个答案:

答案 0 :(得分:4)

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