C++ boost::bind、std::bind和重载函数
我注意到boost::bind与std::bind不同,当其中一个函数没有任何参数时,它可以处理重载函数。我说得对吗?这有文件记录吗C++ boost::bind、std::bind和重载函数,c++,boost,c++11,boost-bind,C++,Boost,C++11,Boost Bind,我注意到boost::bind与std::bind不同,当其中一个函数没有任何参数时,它可以处理重载函数。我说得对吗?这有文件记录吗 #include <boost/bind.hpp> #include <functional> #include <iostream> void foo() { std::cout << "::foo() \n"; } void foo(int) { std::cout << "::
#include <boost/bind.hpp>
#include <functional>
#include <iostream>
void foo()
{
std::cout << "::foo() \n";
}
void foo(int)
{
std::cout << "::foo(int) \n";
}
int main()
{
boost::bind(foo)(); // Ok
boost::bind(foo, 0)(); // Ok
// std::bind(foo)(); // Error
// std::bind(foo, 0)(); // Error
}
#include <boost/bind.hpp>
#include <functional>
#include <iostream>
void foo(int)
{
std::cout << "::foo(int) \n";
}
void foo(const std::string&)
{
std::cout << "::foo(const std::string&) \n";
}
int main()
{
// boost::bind(foo, 0)(); // Error
// boost::bind(foo, "str")(); // Error
// std::bind(foo, 0)(); // Error
// std::bind(foo, "str")(); // Error
}
#包括
#包括
#包括
void foo()
{
std::cout我假设它只是实现细节的一个意外产物,我不认为Boost提供了自动解决正确重载的任何保证
std::bind
是一个用可变模板实现的C++11功能
boost::bind
是为C++03实现的,这意味着它依赖于大量重载函数模板
这两者在实现细节上有很大的不同,因此,我认为它们行为之间的任何差异都是这种差异的结果,而不是有意的和特定的差异
Boost文档仅说明以下内容:
试图绑定重载函数通常会导致错误,因为无法确定要绑定哪个重载
在我的书中,这意味着Boost文档会告诉您,这是“未定义的行为”,无论它是否可以工作(编译),甚至选择正确的重载
据我所知,您应该始终使用显式转换(static\u cast
)来修复您希望选择的重载的签名。对于boost::bind
和std::bind
,这两种实现都是如此,从这个意义上讲,这两种实现都是一致的。它在某种程度上被记录为“接口”->“概要”的一部分部分,其中列出了重载。如您所见,Boost不使用可变模板,因此,当给定这些重载时,显式地:
template<class R> unspecified-2 bind(R (*f) ());
template<class F, class A1> unspecified-3-1 bind(F f, A1 a1);
template<class R, class B1, class A1> unspecified-4 bind(R (*f) (B1), A1 a1);
模板未指定-2绑定(R(*f)();
模板-3-1结合(F,A1);
模板未指定-4结合(R(*f)(B1),A1);
编译器更喜欢带有空参数列表的重载版本,因为它比其他版本更匹配。不过,我不认为这是故意的。第一种情况在MSVC10中可以很好地编译std
和boost
(因为MSVC10不支持可变模板,所以std::bind
的实现方式与boost::bind
类似)
第二种情况不会编译,因为bind
可以解析具有不同算术性的重载,但不能解析仅因参数类型不同而不同的重载