我不知道我做错了什么。从指向基类成员的指针进行模板推导时出现问题 - &DerivedClass::BaseClassMemeber。
完整示例:
#include <vcl.h>
#include <tchar.h>
struct Base
{
int BaseClassMember;
};
struct Derived : public Base
{
};
template<class T1, class T2>
void Test(T1& Param1, T2 T1::* Param2)
{
}
int _tmain()
{
Derived inst;
// Compile error E2285 Could not find a match for 'Test<T1,T2>(B,int A::*) - BCC32
// Error 1 error C2782: 'void Test(T1 &,T2 T1::* )' : template parameter 'T1' is ambiguous - MS VS8
Test(inst, &Derived::BaseClassMember);
// Works great
Test<Derived>(inst, &Derived::BaseClassMember);
return 0;
}
我可以找到几种解决方法,例如额外的测试函数重载带有一个模板参数、static_cast、隐式部分特化(测试)。
但我对为什么编译器不能使用 &DerivedClass::BaseClassMemeber 中明确指定的类的原因感兴趣。就是那个问题。如果您有更优雅的问题解决方案,欢迎。
最佳答案
&Derived::BaseClassMember
的类型为 int Base::*
,而不是 int Derived::*
。引用标准:
The result of the unary
&
operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static memberm
of some classC
with typeT
, the result has type “pointer to member of classC
of typeT
” and is a prvalue designatingC::m
. [... skip ...] [Example:
struct A { int i; };
struct B : A { };
... &B::i ... // has type int A::*i
— end example]
如果您需要此类型,则必须将值转换为 int Derived::*
。
关于c++ - 从指向基类成员的指针进行模板推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22087183/