这是个有点奇怪的问题。我的目标是理解语言设计决策,并确定在c++中反射的可能性。

为什么c++语言委员会没有在语言中实现反射?在不运行在虚拟机上的语言(如java)中反射是否太困难了? 如果要在c++中实现反射,会遇到什么挑战?

我想反射的用途是众所周知的:编辑器可以更容易地编写,程序代码将更小,可以为单元测试生成模拟等等。但是如果你能评论一下反射的用法就太好了。


当前回答

The reason C++ doesn't have reflection is that this would require the compilers to add symbol information to the object files, like what members a class type has, information about the members, about the functions and everything. This essentially would render include files useless, as information shipped by declarations would then be read from those object files (modules then). In C++, a type definition can occur multiple times in a program by including the respective headers (provided that all those definitions are the same), so it would have to be decided where to put the information about that type, just as to name one complication here. The aggressive optimization done by a C++ compiler, which can optimize out dozens of class template instantiations, is another strong point. It's possible, but as C++ is compatible to C, this would become an awkward combination.

其他回答

Reflection requires some metadata about types to be stored somewhere that can be queried. Since C++ compiles to native machine code and undergoes heavy changes due to optimization, high level view of the application is pretty much lost in the process of compilation, consequently, it won't be possible to query them at run time. Java and .NET use a very high level representation in the binary code for virtual machines making this level of reflection possible. In some C++ implementations, however, there is something called Run Time Type Information (RTTI) which can be considered a stripped down version of reflection.

这基本上是因为它是一个“可选的额外项目”。许多人选择c++而不是Java和c#等语言,这样他们可以更好地控制编译器的输出,例如,一个更小和/或更快的程序。

如果您选择添加反射,有各种可用的解决方案。

如果你真的想了解c++的设计决策,可以找一本Ellis和Stroustrup写的《c++注释参考手册》。它并不是最新的标准,但它贯穿了最初的标准,并解释了事情是如何工作的,以及它们是如何实现的。

反射可以是可选的,就像预处理器指令一样。类似的

#pragma启用反射

通过这种方式,我们可以两全其美,没有这个pragma库就可以在没有反射的情况下创建(没有任何开销),然后就由个人开发人员决定他们想要的是速度还是易用性。

在c++中使用反射的情况有很多,而使用模板元编程等编译时结构无法充分解决这些问题。

N3340建议用富指针作为c++中引入反射的一种方式。除此之外,它还解决了一个问题,那就是除非你使用某个功能,否则就不用为它付费。