繁体   English   中英

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

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

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

这将使用不相关类型Bar的参数有效地调用Foo::comp (const Foo& a) 如果我注释掉std::cout << "a = " << as << 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;
}

答案是在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));
    }

您可以看到右侧类型存在不安全的C样式转换“_Arg2_type(__ x)”,因此您的示例编译就像编写它一样:

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

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

暂无
暂无

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

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