为什么std::bitset::size不是静态的

9

我无法想象为什么选择使std::bitset::size成为非静态的。这使得获取constexpr大小变得更加困难;你必须编写类似以下的代码:

template<int val>
struct int_
{
   static const constexpr value = val;
};

template<size_t size>
auto getBitsetSizeIMPL(std::bitset<size>)
{
   return int_<size>{};
}

template<typename BitsetType>
constexpr size_t getBitsetSize()
{
    return decltype(getBitsetSizeIMPL(BitsetType{}))::value;
}

如果它是静态的,你只需要做的就是

BitsetType::size()

并且不会牺牲功能。

我是否缺少历史原因或者我是否缺少技术事实?


1
顺便说一句,你可以使用 BitsetType{}.size() - cpplearner
真的!没想到那个。那样会好得多。但仍然,它不能是静态的吗? - Russell Greene
由于相同的原因,我想std::array::size也不是静态的。上周有人问到这个问题。 - Lightness Races in Orbit
@lightness 得出什么结论? - Russell Greene
@RussellGreene:我不记得了。因此,暗示如果你寻找相关的最近问题,你会找到它:P - Lightness Races in Orbit
1个回答

1
假设一个非 constexprstd::bitset::size 是错误的:
std::size_t size() const; // until C++11
constexpr std::size_t size();  // since C++11, until C++14
constexpr std::size_t size() const; // since C++14)

但是为了使用它们,您必须拥有一个constexpr位集。它不是静态的。 - Russell Greene
你没有回答问题。我知道它是constexpr。我只是好奇为什么他们选择了这个设计选择。 - Russell Greene
@RussellGreene:我不知道,但是使用两个字符{}()来创建一个实例,实际上并没有太多的符号负担。这只是一点小瑕疵。 - Cheers and hth. - Alf
我完全同意。我只是好奇为什么它不是静态的:对于相同的类型,它将始终返回相同的值。 - Russell Greene
@RussellGreene:你可能有所发现。对于std::array也是一样,只不过这里std::tuple_size扮演了自由大小函数的角色。但是它在std::bitset中没有重载。很好奇。 - Cheers and hth. - Alf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接