if constexpr可以用来声明具有不同类型和init-expr的变量吗 [英] Can `if constexpr` be used to declare variables with different types and init-expr

查看:79
本文介绍了if constexpr可以用来声明具有不同类型和init-expr的变量吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

void foo()
{
    if constexpr (...)
        int x = 5;
    else
        double x = 10.0;
    bar(x); // calls different overloads of bar with different values
}

这在D lang中很常见,但是我没有找到有关C ++ 17的信息.

It's common case in D lang, but I didn't found info about C++17.

当然,可以使用类似的东西

Of course, it is possible to use something like

std::conditional<..., int, double>::type x;

,但仅在基本情况下.甚至不同的初始化方法(如上所述)也会造成很大的问题.

but only in elementary cases. Even different initializators (as above) creates big problem.

推荐答案

此代码无法正常工作.问题是,当您调用 bar 时, x 不在范围内.但是有一种解决方法:

There is no way this code could work. The problem is that x is out of scope when you are calling bar. But there is a workaround:

constexpr auto t = []() -> auto {
  if constexpr(/* condition */) return 1;
  else return 2.9;
}();

bar(t);

为了说明一点,它使用立即调用的lambda表达式以及自动返回类型推导.因此,我们在适当位置赋予t值,并且不会超出范围.

To explain a little bit, it uses instantly invoked lambda expression along with auto return type deduction. Therefore we are giving t value in place and it does not get out of the scope.

当然,如果在编译时无法对if语句进行求值,那将是行不通的.而且,如果您想在此lambda中执行一些运行时操作,则不能将t作为constexpr,但它仍然可以工作.

Of course, it wouldn't work if the if statement couldn't have been evaluated at compile time. And if you want to do some runtime operations inside of this lambda you cannot have t as constexpr, but it will still work.

这篇关于if constexpr可以用来声明具有不同类型和init-expr的变量吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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