gpt4 book ai didi

c++ - std::function 与自动调用不同的重载

转载 作者:太空狗 更新时间:2023-10-29 20:34:19 33 4
gpt4 key购买 nike

我有以下代码:

#include <iostream>
#include <functional>

void f(const std::function<void()>&)
{
std::cout << "In f(const std::function<void()>&)." << std::endl;
}

void f(std::function<void()>&&)
{
std::cout << "In f(std::function<void()>&&)." << std::endl;
}

int main()
{
auto func = []() { std ::cout << "func\n"; };
f(func); // calls void f(std::function<void()>&&)

/*const*/ std::function<void()> func2 = []() { std ::cout << "func\n"; };
f(func2); // calls void f(const std::function<void()>&)

f([]() { std ::cout << "func\n"; }); // calls void f(std::function<void()>&&)

return 0;
}

我想知道为什么第一次调用f (当我使用 auto 和 lambda 函数时)调用 void f(std::function<void()>&&)过载而不是 void f(const std::function<void()>&) , 而是由第二次调用 f 调用的当我将变量声明为 ( const ) std::function<void()> .

最佳答案

对于第一种情况,即使用 auto , func 的类型是一种独特的 lambda 闭包类型,不属于 std::function<void()> , 但可以隐式转换为 std::function .

Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

转换后我们将得到一个类型为 std::function<void()> 的右值,并且在 overload resolution 中将右值引用绑定(bind)到右值比将左值引用绑定(bind)到右值更好。 ,然后调用第二个重载。

3) A standard conversion sequence S1 is better than a standard conversion sequence S2 if

c) or, if not that, both S1 and S2 are binding to a reference parameter to something other than the implicit object parameter of a ref-qualified member function, and S1 binds an rvalue reference to an rvalue while S2 binds an lvalue reference to an rvalue

对于第二种情况,func2被声明为 std::function<void()> 的确切类型, 然后为 f(func2);无需转换。作为命名变量 func2是一个左值,不能绑定(bind)到右值引用,然后调用第一个重载。

if an rvalue argument corresponds to non-const lvalue reference parameter or an lvalue argument corresponds to rvalue reference parameter, the function is not viable.

关于c++ - std::function 与自动调用不同的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49148991/

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