c++速记运算符->操作员()

发布于 2024-08-27 19:02:10 字数 128 浏览 12 评论 0原文

假设我有:

Foo foo;

有这个的简写吗?

foo.operator->().operator()(1, 2);

Suppose I have:

Foo foo;

is there a shorthand for this?

foo.operator->().operator()(1, 2);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

暮年慕年 2024-09-03 19:02:10

嗯...是的。 更短形式看起来就像

foo.operator->()(1, 2)

消除operator ->部分...从您到目前为止提供的信息来看,这是不可能的,但如果它被实现我可以猜测它的实现方式(从你的表达来看),那么你无法消除它。

在 C++ 中,表达式中重载 -> 运算符的使用被解释为重复重载 -> 调用链,最终以内置 结束>-> 调用。这意味着在某些时候重载的 -> 必须返回一个指针。您重载的 -> 显然不会返回指针。因此,为了使用它,您别无选择,只能将其明确拼写为 operator ->()

Well... Yes. The shorter form would look as

foo.operator->()(1, 2)

As for eliminating the operator -> part... From the information you supplied so far it is impossible to say, but if it is implemented the way I can guess it is implemented (judging from your expression), then you can't eliminate it.

In C++ the use of overloaded -> operator in an expression is interpreted as a chain of repetitive overloaded -> calls, which eventually ends in a built-in -> invocation. This means that at some point the overloaded -> must return a pointer. Your overloaded -> obviously doesn't return a pointer. So, in order to use it you have no other choice but to spell it out explicitly as operator ->().

深白境迁sunset 2024-09-03 19:02:10

假设您实际上意味着 foo.operator->().operator()(1, 2),并且您可以控制 Foo 类 code>,更简单的形式是 (*foo)(1, 2)。它需要 operator* 来定义它,但因为我们通常期望 foo->bar 等价于 (*foo).bar,看来很有道理。

如果您的 Foo 是某种智能指针类,它指向定义 operator() 的对象,那么这将是调用该对象的 <代码>运算符()。

但是如果没有更多细节(并且如果您没有提供实际上有效的 C++ 表达式 - 您编写的 operator(1, 2) 不可能有效),就不可能回答您的问题。我只是猜测你想做什么。

Assuming you actually meant foo.operator->().operator()(1, 2), and that you have control over the class Foo, a simpler form would be (*foo)(1, 2). It requires the operator* to that defined though, but since we usually expect foo->bar to be equivalent to (*foo).bar, it seems reasonable.

If your Foo is a smart pointer class of some sort, which points to an object which defines an operator(), this would be the most concise way of calling the object's operator().

But without more detail (and without you providing an expression that's actually valid C++ -- there's no way in which operator(1, 2) as you wrote it can be valid), it's impossible to answer your question. I'm just guessing at what you're trying to do.

零度℉ 2024-09-03 19:02:10

好吧,不,但是,假设您对该类具有写权限,您可以定义另一个调用operator()的成员函数,然后您会得到类似的结果:

foo->myfunc(1,2);

您发现自己处于这个位置,这表明您(或写这个类的人)对于运算符重载有点太可爱了。

Well, no, but, assuming you have write permissions to the class, you could define another member function that calls operator(), and then you'd have something like:

foo->myfunc(1,2);

That you find yourself in this position is a sign that you (or the person who wrote this class) is being a bit too cute with operator overloading.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文