lezebulon
lezebulon

Reputation: 8014

store different templated class in the same container

I have the following class:

template<unsigned int offsetX, unsigned int offsetY>
class myClass {
//several int and floats that are computed with offsetX and offsetY
//and other stuff
}

Its size is the same regardless of what are the templated parameters. Can I store instances of myClass<1,1> and myClass<0,0> etc, in the same container? I understand it's not possible when the templated thing is a class, but in this case the layout of the class is always the same

edit : I know I could send offsetX and offsetY to the constructor of the class and have no template but in this case they are known at compile-time

Upvotes: 1

Views: 102

Answers (3)

PiotrNycz
PiotrNycz

Reputation: 24440

Define base class for your template where all of these common ints and floats will be placed.

Use your derived template only to compute base fields. Then you can insert your template instances to container defined with base class. This is called object slicing. In general it is not a a good thing...

Better would be to drop template class and to define template function which will do what is already done by your template c-tor.

template <int x, int y> inline MyClass compute()
{…}

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227608

No you cannot, since the types are different. You can use a common base class and store smart pointers to it, or store boost::any.

class MyBase { .... };

template<unsigned int offsetX, unsigned int offsetY>
class myClass : public MyBase{ .... };

then

std::vector<std::unique_ptr<MyBase>> v;

v.push_back(std::unique_ptr<MyBase>(new myClass<1,1>()));
v.push_back(std::unique_ptr<MyBase>(new myClass<0,0>()));

Upvotes: 2

eq-
eq-

Reputation: 10096

No, you can't. The types myClass<1, 1> and myClass<0, 0> are unrelated.

Upvotes: 0

Related Questions