0

I would like to pass a function of a class as parameter of another class method.

template <typename T, const uint8_t size = 8 * sizeof(T)>
class A {
  [...]

  A& left(const unsigned char _char) { ... }
  A& right(const unsigned char _char) { ... }
}

template <class A>
class B {
  static constexpr unsigned char arr[4] = { 'A', 'C', 'G', 'T' };

  [...]
  
  public:
    std::vector<A> nodes(A a, std::function<A& (const unsigned char)> roll) {
    std::vector<A> array;
    
    for (unsigned char base : bases) {
      A tmp = a;
      // if (member(roll(base))) array.push_back(tmp); This is one idea
      if (member(a.roll(base))) array.push_back(tmp); // This is the second one
    }

    return array;
  }
}

The method left and right are the method that I woult pass as parameter. These two methods I would like to pass as parameters to the nodes method of the B class. I suppose two possible way to do that but in both case I don't know to to that.

What is the best method to do that?

th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50
  • What do you mean by "best", here? – Sam Varshavchik Dec 06 '20 at 21:53
  • @SamVarshavchik The clearest method – th3g3ntl3man Dec 06 '20 at 21:54
  • "Clearest" is entirely opinion based, just like "best". What is clearest to one individual may be confusing to others. If you simply don't know how to do this at all, that's one thing. But dancing around the campfire, asking for "best" or "clearest" ways to do something -- that's asking for opinions, which are explicitly off-topic here. – Sam Varshavchik Dec 06 '20 at 21:57
  • Looks like you want a [pointer-to-member-function](https://en.cppreference.com/w/cpp/language/pointer#Pointers_to_member_functions), but your question leaves a lot or room for interpretation. – super Dec 06 '20 at 21:58
  • @SamVarshavchik Okay, I'm sorry ... I thought there was always a better way to do a certain thing. In this case, as you say, I have no idea how to deal with the problem. – th3g3ntl3man Dec 06 '20 at 22:01
  • Well, there you go. You already have a pointer to cppreference.com's page. There are also plenty of older questions here on stackoverflow.com about passing pointers to class methods, or member functions. Forget about templates, at first. Try to practice how to do that with ordinary classes. Once you understand the syntax, and are comfortable using it, adapting it to templates will be very obvious. The shown templates are already complicated, and the resulting syntax will be too, so I think it's unlikely someone else will go through the trouble of typing out all the voodoo, here. Good luck. – Sam Varshavchik Dec 06 '20 at 22:03
  • Does this answer your question? [Function pointer to member function](https://stackoverflow.com/questions/2402579/function-pointer-to-member-function) – JaMiT Dec 06 '20 at 23:11

0 Answers0