c++对象以字符串形式输出属性名
C++ objects outputs with attribute name as a string
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); }
}
- 递归函数计算序列中的平方和(并输出过程)
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 输出(用于 GraphViz)提升图顶点及其属性,使用具有私有变量的类作为捆绑属性
- boost :: Spirit :: Karma语法:逗号从结构上划定了带有选件属性的输出
- boost属性树xml编写器输出没有结束
- 如何在 c++ 中输出指针对象的属性(具有 2 个或更多属性)
- C++ 提升图形库:输出自定义顶点属性
- C++输出到Windows终端使用cout<<term_cc<color,default,attrib>在Windows上正确输出颜色和属性,但在Linux上不能
- 从文件中读取并存储属性会产生错误的输出
- c++对象以字符串形式输出属性名