C++对象与属性名称输出作为字符串
class myFun(Employee obj, String attribute)
{
//return proper attribute value without using conditions like If-Else, ternary or
// conditional operators like && etc.
}
,如果我现在拨打:C++对象与属性名称输出作为字符串
myFun(obj, “name”);
然后这个功能应该雇员的从对象返回名“OBJ”,这是作为参数传递。所以根据属性值的名称,它应该返回该对象的属性值。
有没有办法在C++中做到这一点,而不使用条件或开关语句?我知道在Python中我们可以使用getattr。
不,C++没有反射,所以没有条件它是不可行的。
您需要实施自己的reflection类行为。例如,你可以在你注册每个属性名称的对象内部有一个映射,也可以有一个函数来获取值(或某物)。
换句话说,它是可行的,但不受该语言支持,因此它不会对您的代码的其他读者而言很短,简单,自动或非常直观。
你可以提供一些示例代码,这已经有效地实现了吗? – 2013-02-28 11:14:23
如果不改变班级结构,这是不可能的。 如果性能并不重要,这里是一个解决办法:
class Employee{
std::map<std::string, std::string> attributes;
/*SNIP*/
public:
void addAttr(std::string attr, std::string value){ attributes[attr] = value; }
std::string getValue(std::string attr){ return attributes[attr]; }
//Use this function if you are using c++11 compiler: std::string getValue(std::string attr){ return attributes.at(attr); }
}
你确定你需要列表吗? – 2013-02-28 12:19:31
反思是可能在C++中,尽管间接)
一些与此相关的文章...
http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf http://replicaisland.blogspot.co.il/2010/11/building-reflective-object-system-in-c.html http://www.vollmann.com/pubs/meta/meta/meta.html
所以,你用反射来实现!当然,这些文章包含您可以使用的示例,可以随时分享任何问题。
你也可以给尝试是否使用了C++来BOOST_FUSION_ADAPT_STRUCT http://boost-spirit.com/dl_more/fusion_v2/libs/fusion/doc/html/fusion/extension/macros/adapt_struct.html
- 框架?在C++中没有'Object'。 Employee如何定义? – 2013-02-28 11:11:03
如果需要按名称访问属性,则应考虑使用“std :: map”。 – Axel 2013-02-28 11:13:53
对不起,对象部分..其基本上是一个类 – 2013-02-28 11:19:37