Constexpr如果使用非模板类型

问题描述 投票:4回答:1
#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中,如果分支应该评估为false,那么程序编译是否应该正常?

c++ c++17 if-constexpr
1个回答
4
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.