简体   繁体   English

重载operator - >()来改变被调用函数的返回值

[英]Overloading operator->() to change return value of called function

Basically I'm doing this: 基本上我这样做:

auto result = from (startNodePtr)
    .to<NodeT1>()
    .to<NodeT2>()
    .to<NodeT3>()
    .fail_with(msg)

chasing pointers. 追逐指针。 You can imagine "from" and "to" returning different templates of a SyntaxSugar class and fail_with returning the result. 您可以想象“from”和“to”返回SyntaxSugar类的不同模板,fail_with返回结果。 Works fine. 工作良好。

But it's not that simple. 但事情并非那么简单。 Depending on the types of node I'm on I need to call some operation on the underlying type. 根据我所在节点的类型,我需要在底层类型上调用一些操作。 like this: 像这样:

auto result = from(startNodePtr)
    .to<NodeT1>()
    .to<NodeT2>() -> SomeOperation()
    .to<NodeT3>()
    .fail_with(msg)

The operations will in turn return a Pointer, which I again need to wrap in SyntaxSugar. 操作将依次返回一个Pointer,我再次需要将其包装在SyntaxSugar中。

how would I overload operator-> correctly to do that? 如何重载operator->正确地执行此操作?

Say my class looks like this: 说我的课看起来像这样:

template<typename Pointer_T>
class SyntaxSugar
{
  Pointer_T ptr;

public:
  explicit SyntaxSugar(Pointer_T ptr_)
    : ptr(ptr_)
  {}

  // all kinds of Syntax Sugar

  // this one I don't get to work:
  auto operator-> () { return SyntaxSugar(ptr.operator->()); }
}

That's amazing, @max-langhof 那太棒了,@ max-langhof

i basically now do 我基本上现在这样做

template<typename Op>
    auto SyntaxSugar::apply(Op func) -> decltype(SyntaxSugar(func(ptr)))
    { 
        if (!ptr) {
            fail();
            return SyntaxSugar(nullptr);
        }
        return SyntaxSugar(func(ptr));
    }

and now I can 现在我可以

auto result = from(startNodePtr)
    .to<NodeT1>()
    .to<NodeT2>()
    .apply([](auto node) { return node->SomeOperation(); })
    .to<NodeT3>()
    .fail_with(msg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM