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);
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.
bitset set() function in C++ STL Parameter: The function accepts two parameters which are described below: index – this parameter specifies the position at which the bit has to be set. The parameter is an optional one.
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.
This is not possible with STL bitset
.
std::bitset<N>
template requires a fixed size in advance (at compile-time)
However, one way you can do this by using boost::dynamic_bitset
Something like following:
#include <iostream>
#include <boost/dynamic_bitset.hpp>
void ABC(boost::dynamic_bitset<> &a)
{
/* for (boost::dynamic_bitset<>::size_type i = 0;
i < a.size(); ++i)
std::cout << a[i]; */
std::cout << a << "\n";
}
int main()
{
std::size_t size= 5; // take any value for 'size' at runtime
boost::dynamic_bitset<> x(size); // all 0's by default
x[0] = 1;
x[1] = 1;
x[4] = 1;
ABC( x );
return 0;
}
See here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With