'An std::function in a class that is set to a function in a class that contains the first class [closed]

Note: this question was edited in a way that is more related to the intend of the question from the first place.

Here is the code:

class SmallClass
{
public:
    std::function<void(SmallClass*)> function;
};

class BigClass
{
public:
    SmallClass smallClass;

    void SomeFunction(SmallClass* smallClassP)
    {
        return;
    }

    BigClass()
    {
        smallClass.function = SomeFunction; // error
    }
};

This doesn't work. Using visual studio it will say "no operator matches these operands | operand types are: std::function<void (SmallClass*)> = void (SmallClass*)". By writing std::bind(&BigClass::SomeFunction, this, &smallClass), it weirdly corrupts smallClass and sets it to NULL. Is there a way to work around this?



Solution 1:[1]

Because SomeFunction acturally has a invisible argument called 'this'.

Write like this:

smallClass.function = std::bind(&BigClass::SomeFunction, this);

or use lambda:

smallClass.function = [this]() { SomeFunction(); };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AtomicGu