无法调用 std::function

Cannot invoke std::function

这段代码让我在 VS2015 更新 1 中出错:

error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'

#include <iostream>
#include <functional>
using std::cout;
class A
{
public:
    virtual void init()
    {
        cout << "A";
    };
};


class B
{
public:
    virtual void init()
    {
        cout << "B";
    };
};

class C : private A, private B
{

    std::function<void()> a_init = &A::init;
    std::function<void()> b_init = &B::init;
public:
    void call()
    {
        a_init();
        b_init();
    }
};

int main()
{
    C c;
    c.call();
    return 0;
}

如果那个 VS 编译器有问题或我的代码有任何想法?
编辑

#include "stdafx.h"
#include <functional>
class A
{
public:
    virtual void inita()
    {
        cout << "A";
    };
};


class B
{
public:
    virtual void initb()
    {
        cout << "B";
    };
};

class C : private virtual A, private virtual B
{

    /*std::function<void()> a_init = &A::init;
    std::function<void()> b_init = &B::init;*/
public:
    void call()
    {
        inita();
    }
};

将函数从 virtual 更改为 static,代码将起作用。您需要 class 的特定实例来调用 non-static 函数。

另一方面,如果你想使用non-static函数,你可以添加以下构造函数:

C(A &a, B &b)
{
    a_init = std::bind(&A::init, &a);
    b_init = std::bind(&B::init, &b);
}

然后像这样在 main 中使用它:

A a;
B b;
C c(a, b);
c.call();

编辑:

如果public继承是可以接受的选项,那么你可以做得更简单。

构造函数:

C()
{
    a_init = std::bind(&A::init, this);
    b_init = std::bind(&B::init, this);
}

用法:

C c;
c.call();

您正在尝试将 non-static 成员函数分配给不带参数的 std::function。这行不通,因为 non-static 成员函数有一个隐含的 this 参数。

如何解决这个取决于你想做什么。如果你想调用调用时提供的任意对象的存储函数,你需要更改 std::function 签名:

std::function<void(A*)> a_init = &A::init;

void call()
{
  a_init(this); // or some other object of type A on which you want to invoke it
}

[Live example]

另一方面,如果您想不带参数调用它,则必须 绑定 类型 A 的对象到 std::function 初始化时:

std::function<void()> a_init = std::bind(&A::init, this);

void call()
{
  a_init()
};

[Live example]