c++ - 为什么允许 std::variant 多次持有同一个类型?

标签 c++

std::variant 的用例可以是什么?多次持有同一种类型?
引用 https://en.cppreference.com/w/cpp/utility/variant
只有开始调用std::get<T>(v) 才能发现问题。 .

最佳答案

假设我们想要表示一个可以是关键字、标识符或符号的标记。因此,一种可能的实现是:

enum TokenType : std::size_t {
    Keyword = 0, Identifier = 1, Symbol = 2
};

using Token = std::variant<std::string, std::string, char>;
现在可以使用,例如:
std::get<TokenType::Keyword>(token)
访问替代方案。
这是否是一个好主意当然还有待商榷,但它确实表明了这种用例的存在。

关于c++ - 为什么允许 std::variant 多次持有同一个类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68109028/

相关文章:

c++ - Visual Studio 2010、Intellisense 和 PCH : what are the alternatives to ugly stdafx. h?

c++ - 声明一个 const 变量作为引用

c++ - libcurl 是否单次加载完整页面?

c++ - 为什么在插入 map 时出现段错误?

c++ - 在 C++ 中使用枚举值作为映射中的条目

c++ - 有没有可靠的方法在 double 中传递微秒时间?

c++ - 如何将二进制转换为十进制? (以一种非常简单的方式)

c++ - gcc 链接器 : which input libraries are used?

c++ - 如何调用在另一个 stackoverflow 中找到的已创建仿函数对象?

c++ - 在 QuantLib 日期类和 C++11/boost Chrono 上