对'if constexpr'的理解有误 [英] Wrong understanding of 'if constexpr'

查看:236
本文介绍了对'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

-std=gnu++17

我对

if constexpr (condition)

是编译过程中的一部分

    } else {
      x
      return num;
    }

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

get discarded and I get no error about the undefined

x

我的理解是错误的,因为"if constexpr"类似于

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

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

如何修改此代码以进行编译?

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

感谢您的帮助

推荐答案

如何修改此代码以进行编译?

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

要修复代码,只需用x删除该行即可.

To fix your code, simply remove the line with x.

我的理解是错误的,这个'if constexpr'类似于[...]

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

是的,您的理解是错误的.来自 cppreference :

Yes, your understanding is wrong. From cppreference:

在模板之外,已完全检查了丢弃的语句. if constexpr不能替代#if预处理指令.

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

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

This means every branch in an if constexpr block must be valid C++, even if it's never going to be used.

这篇关于对'if constexpr'的理解有误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆