Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make a tuple that contains functions

The problem I have is that I need to store functions (pointers to functions) that receive an object (suppose a Obj) and return bool, all in a unique "entity". I came with the idea of making tuples of functions, something like this:

typedef std::tuple< *(bool())(obj), *(bool())(obj) > func_pair;

so the func_pair object store them, but no idea how to write it. Now, if it is possible I want, precisely, to store some methods of the object passed by parameter. Lets say that I have:

class Obj:
  public:
    ...
  private:
    bool func1();
    bool func2();
    ...
}

then the tuple would be {func1, func2}.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have the syntax for function pointers wrong — it should be:

typedef std::tuple< bool(*)(Obj *), bool(*)(Obj *) > func_pair;

However, then you have the problem that methods aren’t functions so method pointers and function pointers are incompatible (you can’t convert between them). So you could instead use method pointers:

typedef std::tuple< bool(Obj::*)(), bool(Obj::*)() > func_pair;

which would allow creating a func_pair as

func_pair { &Obj::func1, &Obj::func2 }

Alternately, you could use std::function which is a flexible "callable" that can be bound to any function pointer or functor object with the appropriate operator() method:

typedef std::tuple< std::function<bool(Obj *)>, std::function<bool(Obj *>) > func_pair;

You can convert method pointers into functor objects with std::bind, but it is usually easier to just use lambdas which are just the right thing to begin with

func_pair { [](Obj *o) { o->func1(); }, [](Obj *o) { o->func2(); } }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading