Why is there no language support in C++ for all C+

2019-05-15 04:43发布

问题:

In C++ it is impossible to implement certain C++ standard library type traits without compiler intrinsics, using the C++ language only. Traits deal directly with C++ types. According to §17.6.1.3.2 freestanding implementations of the C++ standard library must implement <type_traits>. Doesn't this effectively mean that the C++ standard requires non-standard language extensions/compiler intrinsics from all compilers which support want to support freestanding C++ standard library implementations?

Why were such type traits allowed into the standard without support in the core language?

回答1:

There are many aspects of the C++ standard library which cannot be implemented without support from the compiler. For example, type_info. A "freestanding C++ library" implementation can't provide such a type, since it is the result of a keyword-based expression: typeid. The only people who could provide such a thing are compiler writers, since the compiler is the one who has to generate those objects.

The same is true of many other elements of the standard library. exception_ptr, current_exception(s), initializer_list, etc. There's a whole chapter of this stuff in the C++ standard.

Not all components of the standard library can be implemented without compiler support. Type traits are simply one more thing which a freestanding C++ library cannot implement. Not in ISO standard C++.

As for why they didn't provide the tools needed to implement them? Because that would have taken more time. Note that reflection isn't even a fully-formed TS yet, while type-traits have been standard for 5 years now.

It is difficult to specify general tools like reflection. To know exactly what behavior you need and how it should be provided. It's much easier to look at common usage patterns (as exemplified by Boost) and just use them. Type-traits are the low-hanging fruit of reflection.