相关疑难解决方法(0)

std :: function无法区分重载函数

我试图理解为什么std::function无法区分重载函数.

#include <functional>

void add(int,int){}

class A {};

void add (A, A){}

int main(){
        std::function <void(int, int)> func = add;
}
Run Code Online (Sandbox Code Playgroud)

在上面显示的代码中,function<void(int, int)>只能匹配其中一个功能,但它会失败.为什么会这样?我知道我可以通过使用lambda或函数指针到实际函数然后将函数指针存储在函数中来解决这个问题.但为什么这会失败?关于我想要选择哪个功能的上下文不清楚吗?请帮助我理解为什么这会失败,因为我无法理解为什么在这种情况下模板匹配失败.

我得到的编译错误如下:

test.cpp:10:33: error: no viable conversion from '<overloaded function type>' to
      'std::function<void (int, int)>'
        std::function <void(int, int)> func = add;
                                       ^      ~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1266:31: note: 
      candidate constructor not viable: no overload of 'add' matching
      'std::__1::nullptr_t' for 1st argument
    _LIBCPP_INLINE_VISIBILITY function(nullptr_t) : __f_(0) {}
                              ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1267:5: note: 
      candidate constructor not viable: no overload of 'add' …
Run Code Online (Sandbox Code Playgroud)

c++ overload-resolution c++11 std-function

33
推荐指数
3
解决办法
7828
查看次数

为什么没有std :: make_function()?

std::function<>几乎任何可调用的东西都是一个有用的包装器,包括自由函数,lambda,仿函数,成员函数,结果std::bind.但是,在创建a时std::function<>,必须明确指定函数签名(取自此处)

struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;
};

void print_num(int i)
{ std::cout << i << '\n'; }

struct PrintNum {
    void operator()(int i) const
    { std::cout << i << '\n'; }
};

// store a free function
std::function<void(int)> f_display = print_num;

// store a lambda
std::function<void()> f_display_42 = []() { print_num(42); };

// store the result of …
Run Code Online (Sandbox Code Playgroud)

c++ function c++11

15
推荐指数
2
解决办法
2886
查看次数

标签 统计

c++ ×2

c++11 ×2

function ×1

overload-resolution ×1

std-function ×1