How to pass bitsets with different sizes to a function?

pcoder picture pcoder · May 26, 2014 · Viewed 7.5k times · Source

I want to pass bitsets to a function. What size should I assign to the bitset parameter bits in the function prototype if the bitsets have different sizes?

For example:

bitset<3> a;
bitset<4> b;

void ABC(bitset<size> bits){
    ...
}

ABC(a);
ABC(b);

Answer

Mohit Jain picture Mohit Jain · May 26, 2014

You can templatize the function taking bitset as argument.

template <size_t bitsetsize>
void ABC(bitset<bitsetsize> a) {
   ...
}

This templatized function would be generated by compiler only when you use it somewhere in your code. If you use this function for bitsets of different sizes, separate functions would be instantiated for once for each size. So you should take care to avoid code depending on any local state variables (static variables local to function) as the function instances are different.

It is advisable to use a reference or constant reference to avoid object copy.

template <size_t bitsetsize>
void ABC(const bitset<bitsetsize> &a) {
   ...
}

An alternative which may not be fit for your requirements is to use std::vector<bool> instead of std::bitset if possible.