Makk aouu
Makk aouu

Reputation: 78

variable type of a class member

I have an example of a structure which contains the length of 2 parameters of a class TEST

struct Structure 
{
 int length1;
 int length2;
}

The class Test will take the structure in its constructor and this is an example of the body of the class Test

class Test
{
public:
   Test(Structure str);
private:
   std::bitset<*> var1; // by * I mean that the type is not known at this stage
   std::bitset<*> var2;
}

The length of the member var1 is variable from one object to another and it should be determined from the structure str ( the element length1 will be the the length of var1 and the same for var2)

what is the better way to this kind of stuff ?

Upvotes: 0

Views: 65

Answers (1)

Anonymous1847
Anonymous1847

Reputation: 2588

Template parameters need to be known at compile-time. Unless you can somehow make the constructor constexpr and pass it a constant Structure, which may not work, you'll need a dynamic version of the bitset type. For this case you can use vector<bool>. It has a special template specialization for the type bool to compress the storage, so there's 8 bits stored in a byte, like a bitset.

Note that however vector<bool> does not act exactly like other vectors. For one, its operator[] does not return a bool reference, but instead a proxy type that acts like a bool reference in some ways. I would suggest using the reference page for the vector<bool> specialization specifically: https://en.cppreference.com/w/cpp/container/vector_bool .

Upvotes: 3

Related Questions