Search code examples
c++templatesvariant

Is the number of types in a C++ template variant limited?


I'm trying to understand how variants are implemented, and reading:

http://www.codeproject.com/KB/cpp/TTLTyplist.aspx

And I'm getting the impression that I can't write a variant that takes X types; but that the template writer picks some N, and I can only have less than-N types in a variant.

Is this correct?

Thanks!


Solution

  • In C++03, there are no variadic templates. This means yes; you simply have to pick some N to go up to, and live with that.

    In C++0x, there will be variadic templates, so you could use one definition for all X.

    If you're looking to make changing the number easy, you can use Boost.Preprocessor and have it do the work for you:

    #define MAXIMUM_TYPELIST_SIZE 20 // or something
    
    struct empty{};
    
    template <BOOST_PP_ENUM_BINARY_PARAMS(MAXIMUM_TYPELIST_SIZE, typename T, =empty)>
    struct typelist;
    
    template <BOOST_PP_ENUM_PARAMS(MAXIMUM_TYPELIST_SIZE, typename T)>
    struct typelist
    {
        typedef T1 head;
        typedef typelist<
                BOOST_PP_ENUM_PARAMS(BOOST_PP_DEC(MAXIMUM_TYPELIST_SIZE), T)> tail;
        enum
        {
            length = tail::length+1
        };
    };
    

    If MAXIMUM_TYPELIST_SIZE were 5, those macro's would expand to what the article has.

    (Of course, if you're using Boost just use their meta-programming library.)