Search code examples
c++template-specializationderived-classpointer-to-member

C++ Wrong template specialization selected when passing member function pointer of derived class as a parameter


As the title says i'm having some troubles passing a member function pointer inherited from a base class to a specialized template function.

If i don't specify the type when calling the template function with the inherited method as a parameter, the compiler will select the wrong (Base) one:

struct Base {
  void method() {
  }
};

struct Derived: public Base {
  void other_method() {
  }
};

template <typename T> void print_class_name(void (T::*func)()) {
  std::cout << "Unknown" << std::endl;
}

template <> void print_class_name<Base>(void (Base::*func)()) {
  std::cout << "Base" << std::endl;
}

template <> void print_class_name<Derived>(void (Derived::*func)()) {
  std::cout << "Derived" << std::endl;
}

int main(int argc, char** argv) {
  print_class_name(&Base::method);    // output: "Base"
  print_class_name(&Derived::method); // output: "Base"???
  print_class_name(&Derived::other_method); // output: "Derived"
  print_class_name<Derived>(&Derived::method); // output: "Derived"
  return 0;
}

Is it necessary to call the specialized template function specifying the derived class in this case or am i doing something wrong?


Solution

  • method is visible from Derived but is actually a member of Base, therefore the type of &Derived::method is void (Base::*)().

    These statements both print the same value:

    std::cout << typeid(&Base::method).name() << "\n";
    std::cout << typeid(&Derived::method).name() << "\n";