How does the std::is_union implementation work?

637 views Asked by At

I'm currently going through the C++ standard library in some more detail, and I was wondering how the implementation of std::is_union works. In libcxx (LLVM), apart from directly using a possibly built-in __is_union, it is defined as

template <class _Tp> struct __libcpp_union : public false_type {};
template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_union
    : public __libcpp_union<typename remove_cv<_Tp>::type> {};

Similarly, STLPort, although quite old implements it even more minimalistic:

template <class T>
struct is_union
{ };

This seems to always resolve to std::false_type, or even worse, an empty struct, but it doesn't; how is this achieved? In another question, an answer stated that is_union can't be implemented without compiler hooks, but wouldn't this mean that libcxx, STLPort, and probably all major implementations aren't portable to any compiler that doesn't automagically make it work?

1

There are 1 answers

0
Yakk - Adam Nevraumont On BEST ANSWER

Not all of the std library can be implemented in C++.

You skipped the tests for various intrinsics.

There is no way to implment is_union without intrinsics, essentially.

The std library is not a library that ships with C++, it is part of the language. #include <vector> permits certain code to work; no vector header need exist, just the state of the C++ program has to change after the directive.

In practice (by design) it is written and implemented in C++ as a relatively conventional library with the help from intrinsics, and written with reserved tokens to avoid preprocessor conflicts (the __ and _Ty variable names, for example).