How many types can std::variant define?
Asked Answered
B

1

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?

Betti answered 30/9, 2016 at 12:48 Comment(0)
H
9

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]

Hannon answered 30/9, 2016 at 13:15 Comment(7)
"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?Betti
@ValentinHeinitz Answers to your two questions: it does; AFAIK not.Hannon
ОК, great! So it's truly a new C++11 compiler feature not an add-on to the library like boost.Betti
@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.Hannon
@ValentinHeinitz Seems you erroneously think, that std::variant is built-in type.Ber
@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.Whereas
@Yakk It may worth the effort to implement it, say, in clang++. How difficult task is it, what do you think?Ber

© 2022 - 2024 — McMap. All rights reserved.