0
class myFun(Employee obj, String attribute)
{
   //return proper attribute value without using conditions like If-Else, ternary or     
   // conditional operators like && etc.
}

现在如果我打电话:

myFun(obj, “name”); 

那么这个函数应该从作为参数传递的对象“obj”中返回员工的名字。因此,根据属性值的名称,它应该返回该对象的属性值。

有什么方法可以在不使用 if 条件或 switch 语句的情况下在 c++ 中做到这一点?我知道在python中我们可以使用getattr。

4

4 回答 4

3

您将需要实现自己的类似反射的行为。例如,您可以在对象内部有一个映射,您可以在其中注册每个属性的名称,也许还有一个函子来获取值(或其他东西)。

换句话说,它是可行的,但该语言不支持它,因此它不会简短、简单、自动或对您的代码的其他读者来说不一定非常直观。

于 2013-02-28T11:11:14.280 回答
1

不,C++ 没有反射,所以没有条件它是不可行的。

于 2013-02-28T11:09:36.063 回答
0

如果不改变班级的结构,这是不可能的。如果性能不重要,这里有一个解决方法:

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-28T11:16:24.543 回答
0

反射在 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

因此,您可以通过反思实现这种行为!当然,这些文章包含您可以开始使用的示例,请随时分享任何问题。

您也可以尝试 BOOST_FUSION_ADAPT_STRUCT http://boost-spirit.com/dl_more/fusion_v2/libs/fusion/doc/html/fusion/extension/macros/adapt_struct.html

于 2013-02-28T11:22:21.133 回答