在C++中,std::visit 是一个函数,用于在 std::variant 或其他可访问类型的变体中访问其值
首先,需要包头文件。然后,创建一个std::variant 类型的容器(例如,std::vector>)。接下来,使用范围for循环遍历容器,并在每个元素上调用 std::visit`。
以下是一个示例:
#include
#include
#include
int main() {
std::vectorint, std::string>> container = {10, "Hello", 20, "World"};
for (const auto& elem : container) {
std::visit([](const auto& value) {
if constexpr (std::is_same_v<decltype(value), int>) {
std::cout << "Integer: "<< value class="hljs-comment">// 对于 std::string 类型的值
else if constexpr (std::is_same_v<decltype(value), std::string>) {
std::cout << "String: "<< value class="hljs-keyword">return 0;
}
这将输出:
Integer: 10
String: Hello
Integer: 20
String: World
在此示例中,我们使用了 std::visit 来访问 std::variant 容器中的每个元素。对于每种类型,我们都有一个单独的处理分支。注意,我们使用了 if constexpr 和 std::is_same_v 来检查当前值的类型。这样,编译器可以在编译时优化代码,并确保我们不会在运行时进行不必要的类型检查。