考虑这个例子(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;
}发布于 2017-09-11 07:54:34
答案是执行std::bind2:
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++代码。
https://stackoverflow.com/questions/46113869
复制相似问题