【问题标题】:How to return from function lvalue or rvalue based on parameters?如何根据参数从函数左值或右值返回?
【发布时间】:2021-07-06 10:34:35
【问题描述】:

考虑例子:

#include <string>
#include <iostream>

auto get_r_value() { return std::string("hello"); }

int VAL = 15;
int& get_l_value() { return VAL;}

template<typename ...Types> auto&& func(Types... vars) {
    if constexpr (sizeof ... (vars) <= 2) {
        return get_l_value();
    } else {
        return get_r_value();  // warning: returning reference to temporary 
    }
}

int main() {

    auto&& a = get_l_value();
    a = 20;
    std::cout << VAL << std::endl; // print 20
    
    auto&& b = get_r_value();   // auto&& works as expected!
    std::cout << b << std::endl;

    func(1, 2) = 30;  
    std::cout << VAL << std::endl;  // print 30

    std::cout << func(1, 2, 3) << std::endl;  // SEGMENTATION FAULT!
    
    return 0;
}

我们可以看到auto&amp;&amp; 类型在返回类型时不起作用!

有没有办法根据模板参数从函数lvaluervalue返回?

【问题讨论】:

    标签: c++ templates rvalue


    【解决方案1】:

    你可以使用decltype(auto):

    template<typename ...Types> decltype(auto) func(Types... vars) {
        if constexpr (sizeof ... (vars) <= 2) {
            return get_l_value();
        } else {
            return get_r_value();
        }
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      相关资源
      最近更新 更多