如何确定constexpr是否返回引用

时间:2019-03-22 14:17:52

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

如果您有一个if constexpr ()决定做另一件事的函数,那么在一种情况下如何返回左值,在另一种情况下如何返回右值?

以下示例不会在第一个用法行中编译,因为返回类型auto没有引用:

static int number = 15;

template<bool getref>
auto get_number(int sometemporary)
{
    if constexpr(getref)
    {
        return number; // we want to return a reference here
    }
    else
    {
        (...) // do some calculations with `sometemporary`
        return sometemporary;
    }
}

void use()
{
    int& ref = get_number<true>(1234);
    int noref = get_number<false>(1234);
}

2 个答案:

答案 0 :(得分:11)

  

在一种情况下如何返回左值,在另一种情况下如何返回右值?

我想您可以尝试使用<?php $query="SELECT * FROM Products ORDER BY id ASC"; $result=mysqli_query($connect,$query); $image_path = ""; if(mysqli_num_rows($result)>0) { while($row=mysqli_fetch_array($result)) { ?> <div class="item" style="background:white;solid lightgrey;box-shadow: 12px 12px 22px -10px #888888;"> <form action="description.php" method="post" id="item"> <div class="product"> <div class="product-thumb" name = "image" id ="image"> <?php echo '<img class="img-responsive img-fullwidth" src="data:image/jpeg;base64,'.base64_encode( $row["image"] ).'"/>' ?> <input type="hidden" name='product_image' id="product_image" value="<?php echo '<img class="img-responsive img-fullwidth" src="data:image/jpeg;base64,'.base64_encode( $row["image"] ).'"/>' ?>" /> //input closing tag is clashed with img to closing tag </div> <div class="overlay"> <button name="add_to_cart" type="submit" class="btn btn-lg btn-dark btn-theme-colored btn btn-circled text-uppercase font-weight-5" href="shop-cart.html" >Add To Cart</button> </div> </div> </div> </form> </div> <?php } } ?> 和几个括号

decltype(auto)

答案 1 :(得分:4)

std::ref似乎对我有用:

#include <functional>
#include <iostream>

static int number = 15;

template<bool getref>
auto get_number()
{
    if constexpr(getref)
    {
        return std::ref(number); // we want to return a reference here
    }
    else
    {
        return 123123; // just a random number as example
    }
}

int main(int argc, char **argv)
{
    int& ref = get_number<true>();
    int noref = get_number<false>();

    std::cout << "Before ref " << ref << " and number " << number << std::endl;
    ref = argc;
    std::cout << "After ref " << ref << " and number " << number << std::endl;

    std::cout << "Before noref " << noref << " and number " << number << std::endl;
    noref = argc * 2;
    std::cout << "After noref " << noref << " and number " << number << std::endl;
}

Try it online!

正如预期的那样,更改ref会更改number(而不是noref),而更改noref不会更改其他内容。

由于行为是constexpr并已模板化,因此返回std::ref的{​​{1}}会强制其实际进行引用。