簡體   English   中英

提升變體簡單調用常用方法

[英]boost variant simple call to common methods

我有兩個指針,只能設置其中一個,所以我正在考慮使用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。

你或許可以說

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

在c ++ 14中最近的提升。 讓我試試看...

是的,你可以: Live On 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);
}

我經常使用的模式是為訪問者提供處理變量的重載:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM