c++ - 'if constexpr'理解错误

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

我有以下代码

static constexpr bool condition = true;

int square(int num) {
    if constexpr (condition) {
      return num * num;
    } else {
      x
      return num;
    }
}

int main() {
    return square(3);
}

编译为

-std=gnu++17

我的假设

if constexpr (condition)

是编译期间的那部分

    } else {
      x
      return num;
    }

被丢弃,我没有得到关于未定义的错误

x

我的理解是否错误,这个“if constexpr”类似于

#ifdef CONDITION
  return num * num;
#else
  x
  return num;
#endif

我如何修改这段代码以便我可以编译它?

感谢帮助

最佳答案

How do I modify this code that I can compile this?

要修复您的代码,只需删除带有 x 的行即可。

Is my understanding wrong that this 'if constexpr' is something like [...]

是的,你的理解是错误的。来自 cppreference :

Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive.

这意味着 if constexpr block 中的每个分支都必须是有效的 C++,即使它永远不会被使用。

关于c++ - 'if constexpr'理解错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300760/

相关文章:

C++:同一命名空间中类名的标识符未定义

c++ - 有没有办法在所有新的 Qt 项目上强制使用 QT_NO_FOREACH?

opencv - 安卓 : linking to opencv results in SIGBUS (signal SIGBUS: illegal alignment) when exception is thrown

c++ - 类似于 "if constexpr"但用于类定义

c++ - 根据编译器优化和代码性能,`if constexpr` 与 `if`

c++ - 排序多维数组/vector

c++ - 可变参数模板查询

c++ - GCC C++ 错误? (T)x 匹配 X::operator const T&() const 与 clang 的不同

c++ - Constexpr,如果测试一个模板参数

c++ - 如何声明一个没有特定大小的数组?