将PARENT类成员的名称作为模板参数传递

pass name of member of PARENT class as template argument

本文关键字:参数传递 PARENT 成员      更新时间:2023-10-16

如何将父成员的名称传递到模板参数中?

这很难解释,所以我将显示短代码。

示例

此代码的A派生自Mother。我想把母亲场的名字传给B.的模板

它不可编译。我已经标出了发生错误的那一行。

class Mother{
public:
int motherField=3;   
};
class A: public Mother { 
public:
int childField=4; 
}; //note: not virtual inherit
template <class T, int T::*a>
class B{ }; 
int main() { 
B<A,&A::motherField> b;
//^ could not convert template argument '&Mother::motherField' to 'int A::*'
}

如果我从"motherField"改为"childField",它可以编译。

看起来编译器认为Mother::motherField与A::motherField非常不同

问题

我想传递父级的成员,有没有办法让它编译?

动机

B是一个特殊的hashMap。让我们把它命名为AMap。

AMap要求键(A)必须为其专用一个字段(在本例中可能是int,"motherField"/"childField"),以缓存一些索引。

AMap<A,&A::dedicatedField1> b1;  //I omit the value part for simplicity.
AMap<A,&A::dedicatedField2> b2;
A a1;
b1.cache(a1); //b1 read&write a1.dedicatedField1
b2.cache(a1); //b2 read&write a1.dedicatedField2

这会带来很多性能优势。

b1.get(a1);//b1 just read a1.dedicatedField1, then it know where a1 is stored

为了方便起见,我在Mother of a中提供了一个默认的dedicatedField,所以有时我可以将Mother::defaultDedicatedField插入AMap(B)。

因此,a.h不必包含专用字段,所以代码更干净。

指向成员的指针具有其实际成员的类的类型。因此,即使您编写&A::motherField,类型也不是int A::*,而是真正的int Mother::*。编译错误来自类型不匹配。

您必须将指向成员的指针强制转换为您想要的类型:

B<A, static_cast<int A::*>(&A::motherField)> b;

但这在gcc或clang上都不起作用(还不明白为什么),所以最好在B中提供第三个默认类型参数。如果需要的话,您可以使用最后一种类型来指定派生类——比如这里:

template <class C, int C::*a, class T=C> class B { }; 
B<Mother, &A::motherField, A> b;