c++ - 推导出的返回类型

标签 c++ c++14

#include <iostream>
#include <vector>

template<typename Container, typename Index>
decltype(auto)
foo(Container&& c, Index i) {
    return std::forward<Container>(c)[i];
}

template<typename Container, typename Index>
decltype(auto)
bar(Container&& c, Index i) {
    return c[i];
}

int main() {
    std::vector<uint32_t> q{1, 3, 5};
    std::vector<uint32_t> r{2, 4, 6};

    std::cout << "lvalue" << std::endl;
    std::cout << foo(q, 1) << std::endl;
    std::cout << bar(q, 1) << std::endl;

    std::cout << "rvalue" << std::endl;
    std::cout << foo(std::move(q), 1) << std::endl;
    std::cout << bar(std::move(r), 1) << std::endl;
}

foo() 的返回类型有什么区别?和 bar()

std::forward<Container>(c)只保留其“原始”类型。它如何影响转弯类型?在我看来,当c是右值引用,std::forward<Container>(c)[i]仍然返回对第 i 个元素的引用;什么时候c是左值引用,std::forward<Container>(c)[i]仍然返回对第 i 个元素的引用。

我确定我错过了什么。

最佳答案

std::vector::operator[] 没有右值 this 的重载。所以在你的情况下,没有任何变化。

但是对于像这样的类:

template <typename T>
struct S
{
    T operator [](std::size_t) &&;
    T& operator [](std::size_t) &;
    // ...
};

这会有所作为。

关于c++ - 推导出的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56769482/

相关文章:

c++ - WM_NCHITTEST 和主监视器左侧的辅助监视器

c++ - C++ 数组中的垃圾值是否可能为负数?

c++ - 如何为无序映射 C++14 包含更好的位混合器

c++ - 在运行时添加字段 : suffer either vtable-cost or cache miss at destructor

c++ - 智能指针 : Does a 'base' part of an object get created?

c++ - 获取 map 内容作为数组

c++ - 确定重定向套接字打开请求的预期 IP 的 POSIX 调用是什么?

c++ - 调用参数多于参数的函数/仿函数

c++ - 如何在单个 cout 中对多个变量进行 set.precision

c++ - 为什么专门化 type_trait 会导致未定义的行为?