1

This is how I have my code setup:

class SomeClass
{
public:
    std::function<void()> someFunction;
}

AnotherClass.h

class AnotherClass
{
public:
    void anotherFunction();
    void yetAnotherFunction();
    SomeClass someClass;
}

AnotherClass.cpp

void AnotherClass::anotherFunction()
{
    std::cout << "triggerd" << std::endl;
}

void AnotherClass::yetAnotherFunction()
{
    someClass.someFunction = &AnotherClass::anotherFunction; //here
}

This resulted in a compile time error: error C2664: 'std::_Func_class<_Ret>::_Set' : cannot convert parameter 1 from '_Myimpl *' to 'std::_Func_base<_Rx> *' After some research I found that this is a bug from VS2012 (source). So I changed the line labeled "here" to someClass.someFunction = std::mem_fn(&AnotherClass::anotherFunction); just like the solution says in the link. However, now this results in another compile time error: error C2562: 'std::_Callable_obj<_Ty>::_ApplyX' : 'void' function returning a value. So from the research I've found on that error, it means that there is a function declared as void returning a value. This is where I'm stuck because I'm 100% sure I don't have any functions returning a value that shouldn't be plus I didn't get this error before changing the line labeled "here". I not sure if this is another bug in VS2012 but the error does say: std::_Callable_obj<_Ty>::_ApplyX which is obviously not my function.

Does anybody have any information on why this is happening and how I can resolve it?

Thanks.

Community
  • 1
  • 1
MrPlosion1243
  • 67
  • 1
  • 5
  • 2
    Your `std::function` has the wrong function type to hold a member function. Either change that, or bind an instance. – chris Jan 29 '13 at 23:29
  • `AnotherClass::anotherFunction` isn't a function. It's not something you can call. Think about that. – Kerrek SB Jan 29 '13 at 23:40

2 Answers2

5

You are assigning a non-static member function to a function object that expects something returning void and taking no arguments. A non-static member function has an implicit first parameter, which in this case would be of type AnotherClass*. You need an AnotherClass instance to bind to the member function.

In your case, you can bind it to the this pointer:

void AnotherClass::yetAnotherFunction()
{
    someClass.someFunction = std::bind(&AnotherClass::anotherFunction, this);
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

If you want to bind the member-function call this->anotherFunction(), then say:

somceClass.someFunction = std::bind(&AnotherClass::anotherFunction, this);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084