Why does C++ not have reflection?

2019-01-01 09:33发布

This is a somewhat bizarre question. My objectives are to understand the language design decision and to identify the possibilities of reflection in C++.

  1. Why C++ language committee did not go towards implementing reflection in the language? Is reflection too difficult in a language that does not run on a virtual machine (like java)?

  2. If one were to implement reflection for C++, what will be the challenges?

I guess the uses of reflection are well-known: editors can be more easily written, program code will be smaller, mocks can be generated for unit tests and so on. But it would be great if you could comment on uses of reflection too.

14条回答
与风俱净
2楼-- · 2019-01-01 10:23

Reflection in C++ , I believe is crucially important if C++ is to be used as a language for Database Access, Web session handling/http and GUI development. The lack of reflection prevents ORMs (like Hibernate or LINQ), XML and JSON parsers that instancinate classes, Data serialization and many other thigns (where initially typeless data has to be used to create an instance of a class).

A compile time switch available to a software developer during the build process can be used to eliminate this 'you pay for what you use' concern.

I a firmwaredeveloper does not need the reflection to read data from a serial port -- then fine do not use the switch. But as a database developer who wants to keep using C++ I am constantly phased with a horrible, difficult to maintain code that maps Data between data members and database constructs.

Neither Boost serialization nor other mechanism are really solving the reflection -- it must be done by the compiler -- and once it is done C++ will be again tought in schools and used in software that are dealing with data processing

To me this issue #1 (and naitive threading primitives is issue #2).

查看更多
梦该遗忘
3楼-- · 2019-01-01 10:25

Reflection for languages that have it is about how much of the source code the compiler is willing to leave in your object code to enable reflection, and how much analysis machinery is available to interpret that reflected information. Unless the compiler keeps all the source code around, reflection will be limited in its ability to analyze the available facts about the source code.

The C++ compiler doesn't keep anything around (well, ignoring RTTI), so you don't get reflection in the language. (Java and C# compilers only keep class, method names and return types around, so you get a little bit of reflection data, but you can't inspect expressions or program structure, and that means even in those "reflection-enabled" languages the information you can get is pretty sparse and consequently you really can't do much analysis).

But you can step outside the language and get full reflection capabilities. The answer to another stack overflow discussion on reflection in C discusses this.

查看更多
登录 后发表回答