通过模板推导,std::vector<int&> 可行吗?

With template deduction, std::vector<int&> is feasible?

本文关键字:lt int gt vector std      更新时间:2023-10-16

我正在学习C++,现在正在进行引用折叠。然而,我现在有一个疑问:

template <typename T>
std::vector<T>& Foo(T) // value of parameter is unnecessary
{
    static std::vector<T> s_vec_T;
    return s_vec_T;
}
int main()
{
    int i = 0;
    auto get_vec = Foo(i); // suppose Foo() would be Foo<int&>(i)
    return 0;
}

因此,最终Foo() s_vec_T中的静态向量将被实例化为std::vector<int&>。尽管如此,代码运行良好。为什么?我想,没有什么可以处理的参考崩溃。

T将被推导为intiint,所以这是将被推导的类型),所以没有问题。std::vector不能保存引用,所以如果它以某种方式将其推断为int&,它甚至可能无法编译。