Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如果使用非模板类型,则为Constexpr #包括 intfoo(intx){ 如果constexpr(std::is_same_v){ x=std::string(); } } 内部主(空) {返回0;}_C++_C++17_If Constexpr - Fatal编程技术网

C++ 如果使用非模板类型,则为Constexpr #包括 intfoo(intx){ 如果constexpr(std::is_same_v){ x=std::string(); } } 内部主(空) {返回0;}

C++ 如果使用非模板类型,则为Constexpr #包括 intfoo(intx){ 如果constexpr(std::is_same_v){ x=std::string(); } } 内部主(空) {返回0;},c++,c++17,if-constexpr,C++,C++17,If Constexpr,这段代码既不能在GCC 7上编译,也不能在Clang 5上编译: #include <iostream> int foo(int x) { if constexpr (std::is_same_v<decltype(x), std::string>) { x = std::string(); } } int main(void) { return 0; } 错误:无法将赋值中的'std::uCxx11::string{aka std:

这段代码既不能在GCC 7上编译,也不能在Clang 5上编译:

#include <iostream>

int foo(int x) {
    if constexpr (std::is_same_v<decltype(x), std::string>) {
        x = std::string();
    }
}

int main(void)
{ return 0; }
错误:无法将赋值中的'std::uCxx11::string{aka std::uCxx11::basic_string}'转换为'int'
x=std::string();

由于引用行位于constexpr if分支中,该分支的计算结果应为
false
,程序是否应编译良好?

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

这是预期的行为,令人惊讶
如果constexpr
不能以这种方式工作,则仅(大致)针对模板参数请参阅或我同意您的意见。我不明白为什么你写的代码没有被指定工作。我觉得很奇怪。当然,在某些情况下,这是可取的,例如构建设置或特定于目标的设置settings@Justin您认为将
字符串
分配给
int
不起作用是令人惊讶的吗?我会很好奇看到这样的用例…@巴里,我想如果我真的想清楚了,是的,在每种情况下都会是一个bug。但是有几例
if constexpr
没有达到我的预期,除非我弄错了。我想得越多,我就越觉得在那些情况下我没有想清楚。。。。
error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘int’ in assignment
         x = std::string();