简体   繁体   English

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

[英]mem_fun + bind2nd allows to call a method with an argument of an arbitrary type

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

This will effectively call Foo::comp (const Foo& a) with a parameter of an unrelated type Bar . 这将使用不相关类型Bar的参数有效地调用Foo::comp (const Foo& a) Not only does this compile, if I comment out std::cout << "a = " << as << std::endl; 如果我注释掉std::cout << "a = " << as << std::endl; it also somehow works and prints Result: 0 它也以某种方式工作和打印Result: 0

If I do print out the value, than it segfaults, which is fair enough... But why does it compile in the first place? 如果我打印出值,而不是段错误,这是公平的......但为什么它首先编译?

#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;
}

The answer is in the implementation of std::bind2nd: 答案是在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));
    }

You can see that there is an unsafe C-style cast "_Arg2_type(__x)" to the right type, so your example compiles as if it was written: 您可以看到右侧类型存在不安全的C样式转换“_Arg2_type(__ x)”,因此您的示例编译就像编写它一样:

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

which is unfortunately valid C++ code. 这是不幸的有效C ++代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM