2

Take the following class hierarchy:

template<typename T>
class Foo {
public:
    T fooMethod() { ... }
};
class Moo : public Foo<bool> {
    ...
};

If I now somewhere write Moo::fooMethod the compiler will deduce Foo<bool>::fooMethod. How can I deduce Foo<bool> as parent of fooMethod myself before compile time?

Motivation: the compiler will not allow Foo<bool>::fooMethod to be passed as template parameter for bool (Moo::*)() since it will be of type bool (Foo<bool>::*)() in that context. But since I have multiple inheritance I dont know what parent fooMethod will be in, it must be deduced.

B M
  • 3,893
  • 3
  • 33
  • 47

1 Answers1

1

If I understand the problem correctly, it is possible to deduce the class a member function is defined in, using the following trait:

template<typename>
struct member_class_t;

template<typename R, typename C, typename... A>
struct member_class_t <R(C::*)(A...)> { using type = C; };

template<typename R, typename C, typename... A>
struct member_class_t <R(C::*)(A...) const> { using type = C const; };

// ...other qualifier specializations

template<typename M>
using member_class = typename member_class_t <M>::type;

after which you can write

member_class<decltype(&Moo::fooMethod)>

giving Foo<bool>.

To define member_class more generally, you should take into account volatile and ref-qualifiers as well, yielding a total of about 12 specializations. A complete definition is here.

iavr
  • 7,547
  • 1
  • 18
  • 53
  • This simple decomposition is exactly what I was looking for, brilliant! :) Thanks a lot! – B M May 05 '14 at 09:37