KenC
KenC

Reputation:

A template with variable number of types

I want to write a C++ template like this:

template <class Type1, class Type2, class Type3,....>

    class MyClass
    {
    //...
    };

But, "the number of types" is variable.

For example, a user can create an object with 3 types:

MyClass<int, int, int> obj;

or he can create an object with 5 types:

MyClass<int, int, int, int, int> obj;

In other words, I want the user :
1.Indicate the number of fields.
2.Set the types according to the number of fields.

how could I do this?

Thanks in advance.

Upvotes: 3

Views: 2000

Answers (4)

sbi
sbi

Reputation: 224069

What you do is your write that template so that it takes a big enough number of arguments, but give default ones to all of them. Then you use template-meta programming to sift through the arguments and weed out the default ones.

Take Neils advice and buy MC++D. That's how most of us learned this technique.

Upvotes: 0

Khaled Alshaya
Khaled Alshaya

Reputation: 96869

Variadic templates. C++0x :(

Just to mention that you can get around that in current C++. For example, you can take a look at Boost::tuple:

#include <boost/tuple/tuple.hpp>

int main()
{
    boost::tuple<int, double> tuple1(4, 2.0);
    boost::tuple<int, double, double> tuple2(16, 4.0, 2.0);
}

You can't assign a variable number of types to the tuple, boost::tuple allows you up to 10 types only. I think litb showed how to do that in a previous answer but I couldn't find it.

Upvotes: 7

anon
anon

Reputation:

I think you should take a look at Alexandrescu's book Modern C++ Design. Chapter 3 on typelists seems to be pretty near to what you want.

Upvotes: 4

jon hanson
jon hanson

Reputation: 9408

as far as I know the only solution right now is to write a separate template for each case. in some cases you might be able to use an enum to type map or a type list, but we would need to know more about what you want to do with the types first.

Upvotes: 0

Related Questions