英文:
How to declare mem_fn without auto?
问题
如何在之后分配 m
而不使用 auto
来声明?
我只在 cppreference,这里在 SO 以及 这里在 SO 上看到带有 auto
的 mem_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<void(), Class>
std::mem_fn<void, Class>
英文:
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 <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>on godbolt</sub>
Because cppreference says I should use 2 arguments, I tried:
std::mem_fn<void(), Class>
std::mem_fn<void, Class>
答案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<void (Class::*)()>
, 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论