Bitset as the return value of a function

风流意气都作罢 提交于 2019-12-23 23:55:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!