【发布时间】:2015-10-10 17:23:04
【问题描述】:
我目前正在编写一个代码,我想用它从具有大量数据字段的对象中获取数据。我的代码如下所示:
void* get( std :: string field_name )
{
(...)
if( field_name == "wbc" ) { return &(this -> wbc); };
if( field_name == "delay" ) { return &(this -> delay); };
if( field_name == "ntracks" ) { return &(this -> ntracks); };
if( field_name == "ntrackFPix" ) { return &(this -> ntrackFPix); };
if( field_name == "ntrackBPix" ) { return &(this -> ntrackBPix); };
if( field_name == "ntrackFPixvalid" ) { return &(this -> ntrackFPixvalid); };
if( field_name == "ntrackBPixvalid" ) { return &(this -> ntrackBPixvalid); };
(...)
std :: cerr << "Error: EventData.get() is unable to find the field: "
<< field_name << ". " << std :: endl;
exit( -1 );
return NULL;
}
这就是我调用 get() 函数 (C++11) 的方式:
void* ptr = this -> event_field -> get( "ntracks" );
auto n_tracks = (auto)(*ptr);
然而,这给了我一个错误信息...... 有没有办法实现我想要的?
我有非常大的结构,其中包含以下类型的字段:int、double、int*(数组)、double*(数组)、char*(字符串)。
除了手动查找每个函数的所有数据字段,按类型手动过滤掉它们并制作具有不同返回类型的get函数之外,还有其他方法吗?
更新:
指定我想要实现的目标:
我知道类型,但因情况而异。有没有可以用来将类型从类传递给函数的解决方案?
例如:
Class A
{
std :: vector<std :: string> typenames;
std :: vector<std :: string> identifiers;
};
Class B
{
(...)
{
(I want to get the given field of given type (specified in A) from a massive object with lots of fields( and I don't know before runtime which fields I will need)
}
(...)
};
【问题讨论】:
-
你有一个 void 指针,那么编译器怎么知道它指向的底层类型呢?
-
你总是可以
reinterpret_cast<void*>(...)函数中的所有内容。不过,我不确定这对auto n_tracks = (auto)(*ptr);是否有帮助;我想你可能需要再做一个reinterpret_cast回到那里的适当类型。 -
将字段名称隐藏在字符串后面有什么意义?我的意思是,你不能写
this -> wbc代替event_field -> get( "wbc" )吗? -
如果您告诉我们您最终想要达到的目标可能会有所帮助。即使您可以自动将 void 指针转换为特定类型,您仍然可以对结果变量做什么?您不能以相同的方式处理
int和ints 数组,因此无论如何您都没有通过这样做获得任何收益。 -
[OT] 您应该将字段名称作为
const string&传递,因为您不想传递字符串的副本(在堆栈上)和const因为您不打算更改字段名称。
标签: c++ c++11 casting return-value auto