简体   繁体   中英

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?

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM