给定这样的结构:
struct Foo{
std::string name;
int value;
};
我正在寻找一种将类型的实例
以及数据成员名称
都传递为单独参数的方法。
尽管这是错误的语法,但我认为它有助于说明我要完成的工作:
template<typename MemberName>
void Print(Foo foo, MemberName member_name){
std::cout << foo.member_name << '\n';
}
int main(){
Foo foo{"name",100}; //create instance
Print(foo,.name); //prints name
Print(foo,.value); //prints 100
}
如何在C ++中实现?
此外,我无权修改该类型的减速度。
您可能正在寻找指向成员的指针:
#include <string>
#include <iostream>
struct Foo{
std::string name;
int value;
};
template<typename MemberType>
void Print(Foo foo, MemberType Foo::* member_name){
std::cout << foo.*member_name << '\n';
}
int main(){
Foo foo{"name",100}; //create instance
Print(foo, &Foo::name); //prints name
Print(foo, &Foo::value); //prints 100
}
编辑:当然,指向成员的指针在c ++中并不常见,在这种特定情况下,仅传递实际成员值(如Steephen建议)会更好(但也许您想在更复杂的情况下使用它们)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句