我正在创建一个位掩码类来处理超过 64 位的数据。我想在编译时生成掩码。下面编译并运行良好,但在使用 Ctor 设置单个位时在 VS 2017 中吐出错误消息。在 Ming-w64 中运行时没有错误消息。我可以安全地忽略 VS 吗?
#include <type_traits>
#include <array>
// N is number of uint64's required to hold bits, code below simplified for up to 128 bits
template<int N>
class CoreBitmaskBase
{
public:
std::array<uint64_t, N> mBitsets_;
constexpr CoreBitmaskBase() noexcept
: mBitsets_()
{}
// Ctor for setting a single bit
constexpr CoreBitmaskBase(const uint64_t& Bit) noexcept
: mBitsets_(InitSetBit(Bit))
{}
constexpr std::array<uint64_t, N> InitSetBit(const uint64_t& Bit);
};
template<int N>
constexpr std::array<uint64_t, N> CoreBitmaskBase<N>::InitSetBit(const uint64_t& Bit)
{
return std::array<uint64_t, N>({ (uint64_t)1 << Bit });
}
// if setting a bit index > 63, adjust mBitsets_'s second element
template<>
constexpr std::array<uint64_t, 2> CoreBitmaskBase<2>::InitSetBit(const uint64_t& Bit)
{
if (Bit < 64) return std::array<uint64_t, 2>({ (uint64_t)1 << Bit, 0 });
else return std::array<uint64_t, 2>({ 0, (uint64_t)1 << (Bit % 64) });
}
// B is number of bits we need for a mask
template<int B, typename Enable = void>
class CoreBitmask : public CoreBitmaskBase<1>
{
using BaseType = CoreBitmaskBase<1>;
public:
constexpr CoreBitmask() noexcept
{
}
constexpr CoreBitmask(const uint64_t& SetBit) noexcept
: BaseType(SetBit)
{
}
};
// specialization for bitmask larger than 64 bits
template<int B>
class CoreBitmask<B, typename std::enable_if<(B > 64)>::type> : public CoreBitmaskBase<2>
{
using BaseType = CoreBitmaskBase<2>;
public:
constexpr CoreBitmask() noexcept
{
}
constexpr CoreBitmask(const uint64_t& SetBit) noexcept
: BaseType(SetBit)
{
}
};
主要.cpp
#include "CoreBitmask.h"
CoreBitmask<128> Mask1(67); // no warning
constexpr CoreBitmask<128> Mask2(67);
// E0028 expression must have a constant value
// access to uninitialized subobject(member "std::array<_Ty, _Size>::_Elems [with _Ty=uint64_t, _Size=2U]")
最佳答案
我找到了一个解决方案。将 std::move 添加到有问题的 ctor 时,智能感知警告消失,如下所示:
// Ctor for setting a single bit
constexpr CoreBitmaskBase(const uint64_t& Bit) noexcept
: mBitsets_(std::move(InitSetBit(Bit)))
{}
关于c++ - 我可以忽略 "Intellisense: (E0028) expression must have a constant value"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43131050/