提升变体简单调用常用方法

时间:2016-05-28 23:37:15

标签: c++ boost boost-variant

我有两个指针,只能设置其中一个,所以我正在考虑使用boost :: variant,比如:boost::variant<shared_ptr<Type1> shared_ptr<Type2>>。类型1和类型2不同,但它们共享一些功能。例如,Thay都有方法IsUnique

如果我有代码来检查初始化:

ASSERT(type1 != nullptr || type2 != nullptr);
ASSERT(type1 == nullptr || type2 == nullptr);
ASSERT(type1 == nullptr || type1->IsUnique());
ASSERT(type2 == nullptr || type2->IsUnique());

我希望能够用尽可能接近的东西替换它:

ASSERT(variant != nullptr);
ASSERT(variant->IsUnique());

但似乎我必须定义访问者,切换类型。

我是否会遗漏某些内容,是否有模板或某些内容可以让我对当前类型的内容应用某些内容?它可能是c ++ 14。

1 个答案:

答案 0 :(得分:7)

你可能只能说

#include <boost/variant.hpp>
struct A { void some_operation() const {}; };
struct B { void some_operation() const {}; };

using Obj = boost::variant<A, B>;

int main() {
    Obj v;
    boost::apply_visitor([](auto const& obj) { obj.some_operation(); }, v);
}

在c ++ 14中最近的提升。让我试一试......

是的,您可以: Live On Coliru

 struct IsNullThing {
      bool operator()(Null) const { return true; }
      template <typename T> bool operator()(T) const { return false; }

      template <typename... Ts> bool operator()(boost::variant<Ts...> const& v) const {
          return boost::apply_visitor(*this, v);
      }
 };

我经常使用的模式是为访问者提供处理变体的重载:

 IsNullThing isNullThing;

 // and just call it

 MyVariant v;
 bool ok = isNullThing(v);

这样你就可以:

destinationViewController.tables
相关问题