c++对象以字符串形式输出属性名

C++ objects outputs with attribute name as a string

本文关键字:输出 属性 对象 字符串 c++      更新时间:2023-10-16
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 "中的Employee的名称。所以根据属性值的名称,它应该返回对象的属性值。

在c++中有任何方法可以在不使用if条件或switch语句的情况下完成它吗?我知道在python中我们可以使用getattr

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

换句话说,它是可行的,但不被语言支持,所以它不会短,简单,自动或非常直观的其他读者的代码。

不,c++没有反射,所以没有条件是不可行的

反射在c++中是可能的,虽然是间接的;)

与此相关的一些文章…

http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdfhttp://replicaisland.blogspot.co.il/2010/11/building-reflective-object-system-in-c.htmlhttp://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

如果不改变类的结构,这是不可能的。如果性能不是很重要,这里有一个变通方法:

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); }
}