gpt4 book ai didi

c++ - 是否需要 boost::variant 访问者类?

转载 作者:行者123 更新时间:2023-11-30 01:22:47 24 4
gpt4 key购买 nike

我是否需要使用诸如 class Visitor : public boost::static_visitor<> 之类的访问者类?使用 boost::variant?

如果不是,是否有理由不使用访问者?是否有理由更喜欢访问者类(class)?

我问这个问题是因为访问者类似乎是使用 boost::variant 的多余部分。

最佳答案

您不是被迫使用访问者,您可以使用 get<T>() 完美查询基础类型.

这导致了这样的代码:

int foo(boost::variant<int, std::string, Bar> const& v) {
if (int const* i = get<int>(&v)) {
return *i;
}
if (std::string const* s = get<std::string>(&v)) {
return boost::lexical_cast<int>(*s);
}
if (Bar const* b = get<Bar>(&v)) {
return b->toInt();
}

std::abort(); // ?
}

这可以说是丑陋的......而且还有一个问题,如果你突然向变体添加一种类型,你需要检查代码中对它的每一次使用,以检查你是否没有遗漏 if。某处。

另一方面,如果您使用变体,如果您未能处理案例(类型),您将收到编译时错误通知。

在我看来,使用boost::static_visitor是无限优越......虽然我已经使用了get<T>()交替几次;通常当我只需要检查一种(或两种)类型而不关心(根本)所有其他类型时。另一种方法是使用带有 template <typename T> void operator()(T const&) const; 的访问者过载,不一定更干净。

关于c++ - 是否需要 boost::variant 访问者类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com