views:

326

answers:

4

Hi, 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.

+7  A: 

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.

AraK
Unfortunately this only works with a compiler implementing (this part of) C++1x. (Which ones do this, BTW?)
sbi
@sbi do you mean the tuple ? it is in boost, it doesn't need Variadic templates to work that way.
AraK
@AraK: Dang, this was a brainfart. It referred to the "variadic templates" at the top of your posting, not to the rest. Sorry for the confusion. It was late last night.
sbi
GCC 4 supports variadic templates :)
AraK
Ah, thanks!
sbi
A: 

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.

jon hanson
+4  A: 

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.

anon
A: 

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.

sbi