将PARENT类成员的名称作为模板参数传递
pass name of member of PARENT class as template argument
如何将父成员的名称传递到模板参数中?
这很难解释,所以我将显示短代码。
示例
此代码的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;
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将PARENT类成员的名称作为模板参数传递