Type of pointer to member from base class

杀马特。学长 韩版系。学妹 提交于 2019-12-04 11:08:44

A conversion from int A::* to int B::* is allowed, and that's not the problem. The problem is in template argument deduction, as you can see if you try the following program which supplies a template argument <int> for B::foo and compiles, and a non-member function foo2 which produces the same error as B::foo did before.

struct A {
  int x;
};

struct B : public A {
};

template <typename T> class Bar {
public:
  template<typename M> void foo(M T::*p);
};

template<typename M> void foo2(M B::*p);

int main(int, char*[]) {
  Bar<B> bbar;
  bbar.foo<int>(&B::x);
  foo2(&B::x); // error, but foo2<int>(&B::x) would work.
  return 0;
}

I think this situation is not covered by the cases where the compiler is supposed to deduce the template argument <int> on its own. 14.8.2.1p3:

In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow a difference:

  • If the original P is a reference type, the deduced A (i.e., the type referred to by the reference) can be more cv-qualified than A.
  • A can be another pointer or pointer to member type that can be converted to the deduced A via a qualification conversion (conv.qual).
  • If P is a class, and P has the form template-id, then A can be a derived class of the deduced A. Likewise, if P is a pointer to a class of the form template-id, A can be a pointer to a derived class pointed to by the deduced A.

Here "P" is the template function's argument type: M B::*p, where template type parameter M is to be determined. "A" is the type of the actual argument: int A::*. P and A are certainly not a reference or a class, and the sort of pointer-to-member conversion we would need for this to work is not a qualification conversion (which describes only const/volatile manipulations like X* to const X* or int X::* to const int X::*).

So the template argument cannot be deduced, and you should add the <int> explicit template parameter to your code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!