如何模板化变量NAMES,而不是类型? [英] How to template'ize variable NAMES, not types?
问题描述
我的问题是如何对应该使用的类成员的 名称 进行模板化。
my question is about how to template'ize the name of a class member that should be used.
也许简化&伪示例:
Maybe a simplified & pseudo example:
/**
Does something with a specified member of every element in a List.
*/
template<membername MEMBER> // <-- How to define such thing?
void doSomething(std::vector<MyClass> all){
for( i=0; i < all.size(); i++)
all[i].MEMBER++; // e.g.; use all[i].MEMBER in same way
}
/ p>
and
class MyClass{
public:
int aaa, bbb, ccc;
}
和应用程序:
main(){
vector<MyClass> all = ....
// applicate doSomething() to all aaa's
doSomething<aaa>(all); // or:
doSomething<MyClass::aaa>(all); // or:
doSomething<?????>(all);
}
如何模板定义看起来像,我可以切换成员变量在doSomething(。)中访问/修改MyClass的名字aaa,bbb或ccc)?
在我的现实世界中,所有的MEMBER都是相同的类型,如上所述。
How should the template definition looks like, that I can switch which member variable (aaa, bbb or ccc) of MyClass is accessed/modified in doSomething(.) ?
In my real world task all MEMBER are of same type, as above.
谢谢,
Tebas
Thanks, Tebas
推荐答案
模板参数仅限于类型,整数常量,指针/引用
Template parameters are restricted to types, integer constants, pointers/references to functions or objects with external linkage and member pointers -- but no identifiers.
但是你可以使用一个成员指针作为模板参数:
But you could use a member pointer as template parameter:
template<int MyClass::* MemPtr>
void doSomething(std::vector<MyClass> & all) {
for( i=0; i < all.size(); i++)
(all[i].*MemPtr)++;
}
:
doSomething<&MyClass::aaa>(all);
请注意,我更改了 doSomething 函数,按值的向量。
Note that I changed the doSomething function to take a reference instead of accepting the vector by value.
这篇关于如何模板化变量NAMES,而不是类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!