如何根据参数从函数左值或右值返回?

时间:2021-07-06 10:34:35

标签: c++ templates rvalue

考虑示例:

#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&& 类型在返回类型时不起作用!

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

1 个答案:

答案 0 :(得分:2)

您可能会使用 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

相关问题