Constexpr if with non-template types

白昼怎懂夜的黑 提交于 2019-12-10 17:17:08

问题


#include <iostream>

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

int main(void)
{ return 0; }

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();

Since the referenced line is in a constexpr if branch that should evaluate to false, shouldn't the program compile fine?


回答1:


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.



来源:https://stackoverflow.com/questions/47895308/constexpr-if-with-non-template-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!