Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot invoke std::function

This code gives me error in VS2015 update 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;
}

Any ideas if that's VS compiler is buggy or my code?
EDIT

#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();
    }
};
like image 678
There is nothing we can do Avatar asked Dec 20 '25 08:12

There is nothing we can do


1 Answers

You're trying to assign non-static member functions into a std::function taking no arguments. That cannot work, since non-static member functions have an implicit this parameter.

How to solve this depends on what you want to do. If you want to call the stored function on an arbitrary object supplied at call time, you'll need to change the std::function signature:

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]

If, on the other hand, you want to call it without arguments, you will have to bind an object of type A into the std::function at initialisation:

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

void call()
{
  a_init()
};

[Live example]

like image 64
Angew is no longer proud of SO Avatar answered Dec 22 '25 00:12

Angew is no longer proud of SO