mem_fun + bind2nd允许调用具有任意类型参数的方法

cpp*_*lex 7 c++ bind

考虑这个例子(https://ideone.com/RpFRTZ)

这将Foo::comp (const Foo& a)使用不相关类型的参数进行有效调用Bar.这不仅编译,如果我注释std::cout << "a = " << a.s << std::endl;它也以某种方式工作和打印Result: 0

如果我打印出值,而不是段错误,这是公平的......但为什么它首先编译?

#include <functional>
#include <string>
#include <iostream>

struct Foo
{
    bool comp(const Foo& a)
    {
        std::cout << "a = " << a.s << std::endl;
        return a.s == s;
    }

    std::string s;

};

struct Bar
{
    int a;
};


template <class F, class T>
void execute (F f, T a)
{
    std::cout << "Result: " << f (a) << std::endl;

}

int main()
{
    Foo* f1 = new Foo;
    f1->s = "Hello";

    Foo f2;
    f2.s = "Bla";

    Bar b;
    b.a = 100;

    execute (std::bind2nd (std::mem_fun(&Foo::comp), b), f1);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

cyr*_*ril 1

答案就在 std::bind2nd 的实现中:

  template<typename _Operation, typename _Tp>
    inline binder2nd<_Operation>
    bind2nd(const _Operation& __fn, const _Tp& __x)
    {
      typedef typename _Operation::second_argument_type _Arg2_type;
      return binder2nd<_Operation>(__fn, _Arg2_type(__x));
    }
Run Code Online (Sandbox Code Playgroud)

您可以看到有一个不安全的 C 风格转换“_Arg2_type(__x)”到正确的类型,因此您的示例编译时就像编写的一样:

execute (std::bind2nd (std::mem_fun(&Foo::comp), (const Foo&)b), f1);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是有效的 C++ 代码。