-1

I want function f2 in structure node to call function f1 in node instead of global function f1.

#include <iostream>
#include <functional>

int f1()
{
    return 1;
}

int f2()
{
    return f1();
}

struct node
{
    int f1()
    {
        return 2;
    }
    std::function<int()> f2 = ::f2;
};

int main()
{
    node a;
    std::cout << a.f2() << "\n";
    return 0;
}

I want function f2 in structure node to call function f1 in node instead of global function f1.

  • 7
    Can't be done. What's the actual problem you are trying to solve? Maybe there is a better way to solve it. – john Nov 22 '22 at 08:09
  • @Someprogrammerdude I think what the OP is saying, is that they want the `::f2` function to call `node::f1` merely because it has been assigned to `node::f2`. – john Nov 22 '22 at 08:10
  • The problem is that `node::f2` is a kind of alias for the global `::f2` function, so while `node::f2` is indeed a member of `node`, the function itself still isn't. So it will call the global `::f1` function. Why don't you define it as a proper member function of `node` instead? – Some programmer dude Nov 22 '22 at 08:10
  • Extend / implement an override for f2 to accept a callback function. Then pass ::f1 when calling. – nick Nov 22 '22 at 08:30
  • 2
    `node::f2` is not a function. It is a glorified function *pointer*. It points to `::f2`. `::f2` cannot call `node::f1`. If you want `node::f2` to have a mind of its own, you need to make it a function. – n. m. could be an AI Nov 22 '22 at 09:04

1 Answers1

1

You can achieve this by adding a (second) constructor to node which accepts a callable to assign to node::f2. Something like this, passing in a lambda to that constructor to capture the object itself:

#include <iostream>
#include <functional>

int f1()
{
    return 1;
}

int f2()
{
    return f1();
}

struct node
{
    node () = default;
    node (std::function<int()> assign_to_f2) { f2 = assign_to_f2; }

    int f1 ()
    {
        return 2;
    }

    std::function<int()> f2 = ::f2;
};

int main()
{
    node a;
    std::cout << a.f2() << "\n";
    node b ([&b] () { return b.f1 (); });
    std::cout << b.f2() << "\n";
    return 0;
}

Output:

1
2

Live Demo

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48