Question

I'd like to be able to use a single C++ typedef for both member function declarations and for pointers to them used elsewhere. If I could match the structure of non-member functions like the following, it would be perfect:

#include <iostream>

using x_ft = char (int);

// Forward decls both advertise and enforce shared interface.
x_ft foo, bar;

char foo(int n) { return (n % 3 == 0) ? 'a' : 'b'; }
char bar(int n) { return (n % 5 == 0) ? 'c' : 'd'; }

int main(int argc, char *argv[]) {
  // Using same typedef for pointers as the non-pointers above.
  x_ft *f{foo};
  x_ft *const g{(argc % 2 == 0) ? bar : foo};

  std::cout << f(argc) << ", " << g(argc * 7) << std::endl;
}

I don't seem to be able to avoid type quasi-duplication for non-static member functions though:

struct B {
  // The following works OK, despite vi_f not being class-member-specific.
  using vi_ft = void(int);
  vi_ft baz, qux;

  // I don't want redundant definitions like these if possible.
  using vi_pm_ft = void(B::*)(int); // 'decltype(&B::baz)' no better IMO.
};
void B::baz(int n) { /* ... */ }
void B::qux(int n) { /* ... */ }

void fred(bool x) {
  B b;
  B::vi_pm_ft f{&B::baz}; // A somehow modified B::vi_f would be preferable.

  // SYNTAX FROM ACCEPTED ANSWER:
  B::vi_ft B::*g{x ? &B::baz : &B::qux};   // vi_ft not needed in B:: now.
  B::vi_ft B::*h{&B::baz}, B::*i{&B::qux};

  (b.*f)(0);
  (b.*g)(1);
  (b.*h)(2);
  (b.*i)(3);
}

My actual code can't really use sidesteps like "auto f = &B::foo;" everywhere, so I'd like to minimize my interface contracts if at all possible. Is there a valid syntax for naming a non-pointer member function type? No trivial variants of void(B::)(int), void(B::&)(int), etc. work.

Edit: Accepted answer - the func_type Class::* syntax is what I was missing. Thanks, guys!

Was it helpful?

Solution

The syntax you seem to be looking for is vi_ft B::*f.

using vi_ft = void(int);

class B {
public:
    vi_ft baz, qux;
};
void B::baz(int) {}
void B::qux(int) {}

void fred(bool x) {
    B b;
    vi_ft B::*f{ x ? &B::baz : &B::qux };
    (b.*f)(0);
}

int main() {
    fred(true);
    fred(false);
}

Above code at coliru.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top