c++ - 从指向基类成员的指针进行模板推导

标签 c++ templates pointer-to-member template-argument-deduction

我不知道我做错了什么。从指向基类成员的指针进行模板推导时出现问题 - &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 member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::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/

相关文章:

c++ - "error: no matching function for call to"

jquery - jsRender 模板可嵌入 jquery 插件吗?

c++ - 指向数据成员转换的 Constexpr 指针

C++ 指向具有匹配函数签名的任何类的成员函数的指针

c++ - 通过 const & 写入类成员

c++ - 使用Linux pread可以避免 “unavailability of data for reading written by a different thread”吗?

c++ - 混合部分模板特化和默认模板参数

c++ - 如何在需要自由函数的地方传递成员函数?

c++ - C++ 函数样式转换的目的到底是什么?

c++ - 你如何在 3 个部分中使用 c++ 中的 power 函数?