8

I've learned there is a std::variant type in c++17. Looks like there are no predefined data types supported by the variant container but for each variant type the user may define her own data-type set.

std::variant<int, float> v;

I wonder, how long may the list of types be? Does the library has a predefined templates for a maximal number of parameter in Aleksandrescu manner, or is the variant supported by the compiler and the number of types is not limited?

Quentin
  • 62,093
  • 7
  • 131
  • 191
Valentin H
  • 7,240
  • 12
  • 61
  • 111

1 Answers1

8

The maximum number of template parameters is limited by the compiler implementation.

The C++ standard says:

Because computers are finite, C ++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This docu mentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown.

The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance.

...

Template arguments in a template declaration [1024]

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • "The maximum number of template parameters is limited by the compiler implementation" - that's true, but does it apply to std::variant? Doesn't std::variant has its own limitation by the implementation? – Valentin H Sep 30 '16 at 13:24
  • @ValentinHeinitz Answers to your two questions: it does; AFAIK not. – Maxim Egorushkin Sep 30 '16 at 13:28
  • ОК, great! So it's truly a new C++11 compiler feature not an add-on to the library like boost. – Valentin H Sep 30 '16 at 13:56
  • 1
    @ValentinHeinitz `std` implementation of `variant` uses variadic templates which is limited by the compiler limits. Pre-C++11 `boost` implementation used a fixed number of template parameters. – Maxim Egorushkin Sep 30 '16 at 14:18
  • 2
    @ValentinHeinitz Seems you erroneously think, that `std::variant` is built-in type. – Tomilov Anatoliy Sep 30 '16 at 16:52
  • 1
    @Orient Note the compiler is free to implement `std::variant` as a built-in type, so long as it behaves as-if the standard dictates. `std::make_index_sequence` in MSVC2015, for example, is done with built-in operations to generate the resulting sequence, rather than implemented in template meta programming. – Yakk - Adam Nevraumont Sep 30 '16 at 19:14
  • @Yakk It may worth the effort to implement it, say, in `clang++`. How difficult task is it, what do you think? – Tomilov Anatoliy Oct 01 '16 at 06:50