gsf*_*gsf 8 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());
Run Code Online (Sandbox Code Playgroud)
我希望能够用尽可能接近的东西替换它:
ASSERT(variant != nullptr);
ASSERT(variant->IsUnique());
Run Code Online (Sandbox Code Playgroud)
但似乎我必须定义访问者,切换类型.
我是否会遗漏某些内容,是否有模板或某些内容可以让我将某些内容应用于当前类型的内容?它可能是c ++ 14.
你或许可以说
boost::apply_visitor([](auto const& obj) { obj.some_operation(); }, v);
Run Code Online (Sandbox Code Playgroud)
在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);
}
Run Code Online (Sandbox Code Playgroud)
我经常使用的模式是为访问者提供处理变量的重载:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
这样你可以做到:
IsNullThing isNullThing;
// and just call it
MyVariant v;
bool ok = isNullThing(v);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
435 次 |
| 最近记录: |