首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mem_fun + bind2nd允许使用任意类型的参数调用方法

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

Stack Overflow用户
提问于 2017-09-08 10:02:23
回答 1查看 249关注 0票数 7

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

这将有效地使用一个无关类型的Foo::comp (const Foo& a)参数调用Bar。这不仅编译,如果我注释掉std::cout << "a = " << a.s << std::endl;,它还能以某种方式工作并打印Result: 0

如果我打印出值,而不是分段错误,这是很公平的.但是,为什么它一开始就编译呢?

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-11 07:54:34

答案是执行std::bind2:

代码语言:javascript
复制
  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)“到正确的类型,因此您的示例编译时就好像它是编写的那样:

代码语言:javascript
复制
execute (std::bind2nd (std::mem_fun(&Foo::comp), (const Foo&)b), f1);

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46113869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档