问题
I'd like to have an interface whose function returns a bitset:
class IMyInterface
{
public:
virtual std::bitset<100> GetBits() = 0;
};
The problem is that I don't want to force the size of the bitset
. So I think I have to use boost::dynamic_bitset
instead:
class IMyInterface
{
public:
virtual boost::dynamic_bitset<> GetBits() = 0;
};
I have heard that boost::dynamic_bitset
is slower than std::bitset
though. Is there any other way to avoid using dynamic_bitset
and have an interface that returns a std::bitset
whose size is determined by the implementors?
回答1:
First of all, due to its static-ness, std::bitset
is not considered to be a good solution. Apart from boost::
stuff, you may use things like...
template<size_t N>
class IMyInterface {
public:
virtual std::bitset<N> GetBits() = 0;
};
But that would still be too static, no? Well, the standards specify that there's an specialization of std::vector<bool>, that is usually implemented as a dynamic, memory-efficient std::bitset
! So...
#include <vector>
class IMyInterface {
public:
virtual std::vector<bool>& GetBits() = 0;
};
Edit: Made IMyInterface::GetBits()
return a reference for efficiency purposes.
来源:https://stackoverflow.com/questions/32293533/bitset-as-the-return-value-of-a-function