在使用 auto 时通过引用提示编译器 return,而不使用 ->

Hint the compiler to return by reference when using auto, without using ->

我有一个 return 类型设置为自动的函数。如果我想通过引用 return 某些东西,通常我可以简单地用 -> T& 提示编译器。但是,在我的特定情况下,我有一个模板化函数,它具有通过 if constexpr 表达式定义的不同 return 路径。像这样:

template<typename T>
auto fn(T& arg)
{
    if constexpr (std::is_same_v<T, int>)
        return;
    else
        return arg;
}

第二种情况我想returnarg引用。有没有办法提示编译器函数体内的类型? 我知道我可以做 std::ref(arg),但是 returned 类型是一个引用包装器,所以如果我做 auto& res = fn(arg),当我尝试将它用作实际参考。基本上我想要通过 -> T& 获得的香草行为,但是对于可以 return 各种类型的函数,所以我想在函数体内提供提示。

这就是 decltype(auto) 的用途。只需将您的签名更改为

template<typename T>
decltype(auto) fn(T& arg)

改用 decltype(auto),它计算出您正在 return 的表达式的确切类型:

template<typename T>
decltype(auto) fn(T& arg)
{
    if constexpr (std::is_same_v<T, int>)
        return;
    else
        return arg;
}
  • 当调用int i; fn(i);时,return类型将是void

  • 当调用float f; fn(f);时,return类型将是float&

live example on godbolt.org with static_assert evidence