在C ++结构中打印所有字段的值 [英] Printing values of all fields in a C++ structure
问题描述
考虑一个简单的结构:
struct abc
{
int a;
char b;
}
我在一个定义为其结构的变量中得到了一些值,现在我想以打印以下内容。
* a = [某些值]
b = [某字符] *
对于任意结构,无需写入转储... )函数为我遇到的每个结构?
看来你已经找到了解决方案,
你所要求的是 Reflection
,即一个对象描述自身的能力。 p>
大多数语言通过元数据实现反射,在python中,例如对象的函数和属性存储在字典元素中。
C ++没有任何本机反射系统,不像C#或Java,这防止(例如)这种自动打印/序列化或反序列化。
C ++有非常强大的元编程支持,允许我们(通过使用模板)模拟反射(在编译时)。这通常使用 Boost.Fusion 完成,该库
正如您的链接中显示的示例, BOOST_FUSION_ADAPT_STRUCT
宏允许您采用标准 struct
,并赋予它所需的接口作为Fusion.Sequence。
另一个例子是使用 Fusion.Vector
或 Fusion.Map
存储类的属性,然后将此Sequence显示为自动打印/序列化/反序列化方法。
但是,这个系统有一个限制:元编程与OO编程不能很好地结合。
struct Base {char一个; }; // Adapt
struct Derived:Base {char b; }; // Adapt
void print(Base const& b){boost :: fusion :: for_each< Base>(b,Print }
将只打印 Base
(这里 a
)。当使用多态性时,您需要在某一点或另一点使用 virtual
方法:)
Consider a simple structure:
struct abc
{
int a;
char b;
}
I got some value in a variable defined as its structure, and now I want to print the below.
*a = [some value]
b = [some character]*
What is the best way to achieve this for an arbitrary structure without having to write a dump...(...) function for each of the structure I encounter?
It seems you already found the solution, but I'll expand a bit.
What you are calling for is called Reflection
, ie the ability for an object to describes itself.
Most languages implement reflection thanks to metadata, in python for example the functions and attributes of an object are stored in a dictionary element.
C++ does not have any native reflection system unlike C# or Java, which prevents (for example) this kind of automatic printing / serialization or deserialization.
However, C++ has very powerful metaprogramming support which allows us (through the use of templates) to emulate reflection (at compile-time). This is usually done using Boost.Fusion, this library being meant for crossing over from compile-time to run-time.
As the example demonstrated in your link, the BOOST_FUSION_ADAPT_STRUCT
macro allows you to take a standard struct
and give it the required interface to be treated as a Fusion.Sequence.
Another example would be to use Fusion.Vector
or Fusion.Map
to store the attributes of the class and then expose this Sequence to automatic print/serialization/deserialization methods.
There is a limitation to this system however: Metaprogramming does not mesh well with OO-programming.
struct Base { char a; }; // Adapt
struct Derived: Base { char b; }; // Adapt
void print(Base const& b) { boost::fusion::for_each<Base>(b, Print()); }
will only print the member of Base
(here a
). When using polymorphism, you need to use virtual
methods at one point or another :)
这篇关于在C ++结构中打印所有字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!