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

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

有没有办法根据模板参数从函数左值右值返回?

最佳答案

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

关于c++ - 如何根据参数从函数左值或右值返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68268969/

相关文章:

c++ - 具有 std::atomic 成员变量的类的复制构造函数/赋值运算符出错

c++ - 将字符串的子部分转换为 int C++

c++ - 错误 : invalid conversion from ‘void*’ to ‘test::apr_size_t* {aka long unsigned int*}’ [-fpermissive]

c - 是否可以在同一行中对其进行数学运算时获取变量的地址

c++ - 右值引用的错误转发

c++ - nullptr 右值如何

php - in_array 的随机错误

c++ - 一般返回一个可选的<T>/nullopt

c++ - 对于类模板,std::enable_if 相对于 static_assert 的优势是什么?

c++ - 包装一个类型,但保留其关于函数重载的行为?