c++ - 为什么从 std::mem_fn 返回的可调用对象可以用于对象和 shared_ptr?

标签 c++ c++11 c++14

以下代码works ,但我不明白为什么会这样。

#include <functional>
#include <iostream>
#include <memory>

struct foo
{
    int get_val() const
    {
        return 42;
    }
};

int main()
{
    foo obj;
    std::shared_ptr<foo> ptr = std::make_shared<foo>();

    const auto getter = std::mem_fn( &foo::get_val );

    std::cout << getter( obj ) << std::endl;
    std::cout << getter( ptr ) << std::endl;
}

为什么getter可以用在objptr上?我希望它只适用于 obj

最佳答案

来自std::mem_fn cppreference page :

Function template std::mem_fn generates wrapper objects for pointers to members, which can store, copy, and invoke a pointer to member. Both references and pointers (including smart pointers) to an object can be used when invoking a std::mem_fn.

简短的回答:因为标准是这么说的。

我猜它只是一个更方便和通用的接口(interface),例如,您可以编写一个调用 std::mem_fn模板函数,它将使用引用和指针:

const auto getter = std::mem_fn( &foo::get_val );

template <typename T>
void call_getter(T&& x)
{
    // do something
    getter(x);
    // do something
}

int main()
{
    foo obj;
    std::shared_ptr<foo> ptr = std::make_shared<foo>();

    call_getter( obj );
    call_getter( ptr );
}

在上面的例子中你只需要一个call_getter的重载。

关于c++ - 为什么从 std::mem_fn 返回的可调用对象可以用于对象和 shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41569844/

相关文章:

c++ - 获取包含头文件中声明的实体定义的源文件名?

c++ - std::shared_ptr 的线程安全

c++ - 在 std::bind 和 std::thread 中 move 语义/行为

c++ - 多态性中基类缺少虚拟析构函数 = 资源泄漏?

c++ - 如何在模板参数中将 std::result_of 转换为 decltype

c++ - 由于链式前缀,Visual Studio 2017 Linux Makefile 项目无法构建

c++ - 构造函数右括号处的无法访问的代码

c++ - 将不可复制的闭包对象传递给 std::function 参数

c++ - 如何从 C++ 中的整数除法返回 double ?

c++ - 具有多个模板参数错误的模板部分特化