[英]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.