如何声明`mem_fn`而不使用`auto`?

huangapple go评论49阅读模式
英文:

How to declare mem_fn without auto?

问题

如何在之后分配 m 而不使用 auto 来声明?

我只在 cppreference这里在 SO 以及 这里在 SO 上看到带有 automem_fn()

#include <iostream>
#include <functional>

class Class
{
public:
    void display() { std::cout << "display" << std::endl; }
};

int main()
{    
    auto m = std::mem_fn(&Class::display);
    Class instance;
    m(instance);
}

<sub>在 godbolt 上</sub>

因为 cppreference 上说我应该使用 2 个参数,我尝试了:

  • std::mem_fn&lt;void(), Class&gt;
  • std::mem_fn&lt;void, Class&gt;
英文:

How to declare m without auto for later assignment?

I only see mem_fn() with auto on cppreference, here on SO and here on SO.

#include &lt;iostream&gt;
#include &lt;functional&gt;

class Class
{
public:
    void display() { std::cout &lt;&lt; &quot;display&quot; &lt;&lt; std::endl; }
};

int main()
{    
    auto m = std::mem_fn(&amp;Class::display);
    Class instance;
    m(instance);
}

<sub>on godbolt</sub>

Because cppreference says I should use 2 arguments, I tried:

  • std::mem_fn&lt;void(), Class&gt;
  • std::mem_fn&lt;void, Class&gt;

答案1

得分: 3

如果你仔细阅读你的cppreference链接,它对返回值说"/* unspecified */"。这意味着,每个编译器供应商可以按照他们想要的方式实现它。所以,auto 是一个非常好的选择。

你可以使用[CppInsights](https://cppinsights.io/lnk?code=I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8ZnVuY3Rpb25hbD4KCmNsYXNzIENsYXNzCnsKcHVibGljOgogICAgdm9pZCBkaXNwbGF5KCkgeyBzdGQ6OmNvdXQgPDwgImRpc3BsYXkiIDw8IHN0ZDo6ZW5kbDsgfQp9OwoKaW50IG1haW4oKQp7。它目前在gcc 12.2、clang 14.0.0和MSVC 19(都使用C++20)上运行正常。但由于这是一个实现细节,可能不会持续太久。

结论:在这里使用auto 是完美的。你不需要理解每种类型的细节。有时,它只是起作用。

这就像一个小孩子在秋千上玩耍:他们可以在秋千上玩得开心,而不需要理解重力。所以对于你来说,只需愉快地使用mem_fn(),而不需要理解类型的内部细节。

英文:

If you read your cppreference link carefully, it says /* unspecified */ for the return value. That means, each compiler vendor can implement it like they want. So auto is a very good choice.

You can use CppInsights to figure out what it compiles to: std::_Mem_fn&lt;void (Class::*)()&gt;, which is an internal type. Don't use this type.

If you plug that back to Godbolt, it currently works on gcc 12.2, clang 14.0.0 and MSVC 19 (all with C++20). But since this is an implementation detail, it may not last long.

Conclusion: using auto here is perfect. You don't need to understand the details of each and every type there is. Sometimes, it just works.

It's like a small child using a swing: they can have fun on the swing without understanding gravity. So for you: you can just have fun using mem_fn() without understanding the internals of the type.

huangapple
  • 本文由 发表于 2023年2月24日 06:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定