位集作为函数的返回值 [英] Bitset as the return value of a function
问题描述
我想要一个接口,该接口的函数返回一个位集:
I'd like to have an interface whose function returns a bitset:
class IMyInterface
{
public:
virtual std::bitset<100> GetBits() = 0;
};
问题是我不想强制bitset
的大小.所以我认为我必须改用boost::dynamic_bitset
:
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;
};
我听说boost::dynamic_bitset
比std::bitset
慢.还有其他方法可以避免使用dynamic_bitset
并具有一个返回std::bitset
且其大小由实现者确定的接口吗?
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?
推荐答案
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;
};
但是那仍然太静态了,不是吗?好吧,标准指定了std::vector<bool>
的专业化,即通常实现为动态的,内存有效的std::bitset
!所以...
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;
};
编辑:为提高效率而制作的IMyInterface::GetBits()
返回参考.
Edit: Made IMyInterface::GetBits()
return a reference for efficiency purposes.
这篇关于位集作为函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!