【问题标题】:How to determine if a boost::variant variable is empty?如何确定 boost::variant 变量是否为空?
【发布时间】:2015-09-28 00:39:39
【问题描述】:

我已经定义了一个 boost::variant var,如下所示:

boost::variant<boost::blank, bool, int> foo;

此变量在实例化但未初始化时具有boost::blank 类型的值,因为boost::blank 是传递给模板化 boost::variant 的第一个类型。

在某些时候,我想知道foo 是否已被初始化。我试过这个,但没有好的结果:

if (foo) //doesn't compile
if (foo != boost::blank()) //doesn't compile
if (!(foo == boost::blank())) //doesn't compile

我认为值得注意的是,当 foo 已初始化(例如,foo = true)时,可以通过执行 foo = boost::blank(); 来“重置”。

如何检查foo 是否已初始化,即它的类型与boost::blank 不同?

【问题讨论】:

  • bool const is_blank = boost::get&lt;boost::blank&gt;(&amp;foo)
  • @PiotrS。它有效,但我不太明白为什么。需要详细说明吗?
  • @PiotrS.: boost::variant&lt;comment, answer&gt; foo(getWhatThatShouldHaveBeen()); assert(foo.which() == 1);
  • @FerranMG:为什么不阅读文档???
  • @FerranMG:我的回答非常便宜。有问题吗?

标签: c++ boost variant


【解决方案1】:

当第一种类型为“活动”时,foo.which() == 0。使用它。

返回:从零开始的索引到包含类型*this 的有界类型集合中。 (例如,如果在包含std::stringvariant&lt;int, std::string&gt; 对象上调用,which() 将返回1。)

(http://www.boost.org/doc/libs/1_58_0/doc/html/boost/variant.html#idp288369344-bb)

【讨论】:

  • 这可行,但如果 boost::variant 定义中的类型顺序发生变化,最终可能会导致问题。它实际上总是可以正常工作(更重要的是,因为我试图确定变量何时为boost::blank 类型,这更有意义作为第一种类型),但我认为boost::get&lt;boost::blank&gt;(&amp;foo) 会更如果它与foo.which() == 0 一样便宜,则为完整的解决方案。可悲的是,我想我将不得不在假设问题或实际开销之间做出选择,所以我最终可能会使用which
  • +1 并同意。我仍然在回答中展示了访问者的方法,因为这样的担忧通常源于恐惧。而恐惧源于缺乏经验。访客不必吓人:)
【解决方案2】:

您可以定义一个访问者来检测“空白”:

struct is_blank_f : boost::static_visitor<bool> {
   bool operator()(boost::blank) const { return true; }

   template<typename T>
   bool operator()(T const&) const { return false; }
};

像这样使用它:

bool is_blank(my_variant const& v) {
   return boost::apply_visitor(is_blank_f(), v);
}

【讨论】:

  • 我喜欢这个解决方案,因为它是完整的,但对于我的用例,我需要避免调用访问者会增加的开销。不过,谢谢。
  • @FerranMG 我敢打赌:它不会增加开销。在启用优化的情况下进行编译。
  • 看起来0==which() 检查无论如何都会赢,从生成的程序集(clang 3.6 和 gcc 5.x)中猜测。尝试进行基准测试,但很难在 which() 检查中获得有用的测量结果:github.com/rmartinho/nonius/issues/20
猜你喜欢
  • 2011-07-15
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 2011-02-08
  • 2011-07-13
相关资源
最近更新 更多