gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:13:05 25 4
gpt4 key购买 nike

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

这很难解释,所以我将展示简短的代码。

示例

此代码具有从 Mother 派生的 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 非常不同

问题

我想传递parent的成员,有什么方法可以编译吗?

动机

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

为方便起见,我在A的Mother中提供了一个默认的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;

关于c++ - 将 PARENT 类成员的名称作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37698409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com