考虑示例:
#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();
}
}
关于c++ - 如何根据参数从函数左值或右值返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68268969/