gpt4 book ai didi

c++ - 两个带参数包的函数的重载解析

转载 作者:太空狗 更新时间:2023-10-29 23:43:47 25 4
gpt4 key购买 nike

请考虑以下两个重载:

template<typename T, typename ...Args>
void f(std::vector<T>&& v, Args&& ...args)
{
std::cout << "f taking a vector + parameter pack\n";
}

template<typename ...Args>
void f(Args&& ...args)
{
std::cout << "f taking a parameter pack\n";
}

现在,对于以下片段,选择了预期的重载:

std::vector<int> v{1, 2, 3};
f(std::move(v), 3.0);

(输出:f 采用 vector + 参数包)

对于以下情况,选择第二个重载:

std::vector<int> v{1, 2, 3};
f(v, 3.0);

(输出:f 接受参数包)

通用引用 vector 参数也绑定(bind)到左值引用,那么为什么在这种情况下只使用参数包的重载会受到青睐? 更新:查看已接受的答案, vector 参数是通用/转发引用的假设是错误的。

最佳答案

The universal reference vector parameter binds to an lvalue reference as well

不,这不是 universal reference .

4) If P is an rvalue reference to a cv-unqualified template parameter (so-called "forwarding reference"), and the corresponding function call argument is an lvalue, the type lvalue reference to A is used in place of A for deduction (Note: this is the basis for the action of std::forward Note: in class template deduction, template parameter of a class template is never a forwarding reference (since C++17)):

所以对于

template<typename T, typename ...Args>
void f(std::vector<T>&& v, Args&& ...args)

请注意 v不是对模板参数的右值引用 T ,但是 std::vector<T> .所以v “只是”一个右值引用,因此不能绑定(bind)到左值。

关于c++ - 两个带参数包的函数的重载解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41312313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com