促进共同方法变异简单的调用 [英] boost variant simple call to common methods

查看:173
本文介绍了促进共同方法变异简单的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有只有一个可以设置两个指针,所以我使用boost ::变种考虑,说:的boost ::变体LT; shared_ptr的<&类型1 GT; shared_ptr的< 2型>> 。 1型和2是不同的,但是它们共享某些功能。大公例如,两者有方法 isUnique设置

I have two pointers that only one of them can be set, so I am considering using boost::variant, say: boost::variant<shared_ptr<Type1> shared_ptr<Type2>>. Type 1 and 2 are different but they share some functionality. Thay for example, both have the method IsUnique.

如果我有code,检查初始化:

If I have the code to check the initialization:

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

我希望能够与尽可能接近的东西来替代它:

I would expect to be able to replace it with something as close as possible to:

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

但似乎我要定义的游客,就类型的开关。

But it seems that I have to define visitors, make switching on types.

难道我错过了什么,有没有一个模板或东西,让我申请到的东西无论当前类型是什么?这可能是C ++ 14。

Do I miss something, is there a template or something that will allow me to apply something to whatever the current type is? It could be c++14.

推荐答案

您可能能够只是说

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

在C ++ 14最近的推动作用。让我来试试吧...

in c++14 with recent boost. Let me try it out...

是的,你可以: <大骨节病> 住在Coliru

#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);
}


一个模式我用了很多是给访问者处理该变种的过载:


A pattern I use a lot is to give the visitor an overload that handles the variant:

 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);
      }
 };

这样,你可以这样做:

This way you can do:

 IsNullThing isNullThing;

 // and just call it

 MyVariant v;
 bool ok = isNullThing(v);

这篇关于促进共同方法变异简单的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆