c++ - 映射的运算符 [] 无法使用作用域枚举作为键进行编译,但它的 at() 函数有效。为什么会模棱两可?
问题描述
我的代码如下所示:
enum class MyTypes {
TYPE_1 = 1,
TYPE_2 = 2,
TYPE_3 = 3
};
static const std::regex reg1("some unique expression");
static const std::regex reg2("some unique expression");
static const std::regex reg3("some unique expression");
static const std::map<MyTypes, std::regex> ValidSets = {
{MyTypes::TYPE_1, reg1},
{MyTypes::TYPE_2, reg2},
{MyTypes::TYPE_3, reg3}
};
static const auto match = [&](const std::string& str, const std::regex& reg) -> bool {
std::smatch base_match;
return std::regex_match(str, base_match, reg);
};
template<MyTypes TYPE = MyTypes::TYPE_2> // defaulting to a specific type
class Foo {
std::string sequence_{""};
public:
const std::uint16_t Type = static_cast<uint16_t>(TYPE);
Foo() = default;
Foo(const std::string_view sequence) {
assert(!sequence.empty() && "invalid input, must contain at least 1 character.");
// Fails to compile
assert(match(sequence.data(), ValidSets[TYPE]) && "invalid sequence set for this type.");
// Works
assert(match(sequence.data(), ValidSets.at(TYPE)) && "invalid sequence set for this type.");
sequence_ = sequence;
}
};
然后我将尝试这样使用它:
int main() {
Foo bar_d("some character sequence"); // must match the regex for the default type
Foo<Type::TYPE1> bar_1("some character sequence"); // must match the regex for type 1
Foo<Type::TYPE3> bar_3("some character sequence"); // must match the regex for type 3
return 0;
}
但是,ValidSets[TYPE]
在 Visual Studio 2017 编译器错误中无法编译C2678
。然而,当我更改它以使用它时,ValidSets.at(TYPE)
它编译并执行得很好......
为什么一个编译失败而另一个工作?
解决方案
推荐阅读
- javascript - 删除“短语”最后一个实例之前或之后的字符
- vb.net - 读取最后 2 行文本文件 VB.Net Win Forms
- c# - 结合 .Contains 和 .Like
- mysql - Yocto 项目:如何将 MYSQL 添加到我的 Linux 操作系统映像中?
- javascript - 如何将数组推入数组?
- python - Beautifulsoup 只返回 100 个元素
- java - 如何等待页面加载 selenium java
- html - 当我将鼠标悬停在 div 上时,如何使链接和文本出现?
- python - 为什么 cv2.imwrite 方法为 mnist 测试图像数据集写一个黑色方块?
- sql - Oracle SQL:使用 count() 和 group by() 将两个查询连接到一个结果集中