2011-07-31 73 views
2

我想创建下面看到的这些函数模板。他们的目的是比较仿函数,但我需要介绍boost.bind类仿函数的一个特例。模板重载(参数数量不同)

template<typename R, typename F, typename L> 
void compare(boost::_bi::bind_t<R, F, L>& lhs, boost::_bi::bind_t<R, F, L>& rhs) 
{ 
    std::cout << lhs.compare(rhs) << std::endl; 
} 

template<typename T> 
void compare(T lhs, T rhs) 
{ 
    std::cout << (lhs == rhs) << std::endl; 
} 

的问题是,当我做compare(boost::bind(func, 1), boost::bind(func, 1)),编译器会尝试使用第二个模板。如果我注释掉第二个,它会正确使用专门用于boost.bind类型的那个,并且一切都会正常工作。

如何让它选择正确的功能模板使用?

+1

它看起来像你依靠的是一种类型是一个推动实现私人类型。你确定你正确的类型适合你传递的内容吗?如果需要使用第一个模板进行任何形式的隐式转换,那么第二个模板将是首选的,因为它可以用原始类型实例化,因此可以更好地匹配。 –

+0

我首先做了'int i = boost :: bind(func,1)'来让编译器告诉我什么绑定返回。此外,[function_equal模板](http://www.boost.org/doc/libs/1_47_0/boost/bind/bind.hpp)也将bind_t作为参数,因此我也应该安全地做到这一点。 –

+2

刚查过'boost :: bind',它通过值返回它的参数,所以'compare(boost :: find(func,1),boost :: bind(func,1))'不应该使用第一个模板作为您不能将临时绑定到非const引用。如果你给第一个添加const,那么它应该是OK的。至于为什么它可以工作,如果你注释掉更一般的模板,我不太确定。在我的实现中,当通用模板被实例化时,我得到一个错误。 –

回答

1

boost::bind返回一个不能绑定到非const引用的值。您的更好的专业模板需要参考价值或const参考,否则将不会在通话中考虑:compare(boost::bind(func, 1), boost::bind(func, 1))

该测试程序在我的平台上编译和正确工作。

#include <boost/bind/bind.hpp> 
#include <iostream> 
#include <ostream> 

template<typename R, typename F, typename L> 
void compare(const boost::_bi::bind_t<R, F, L>& lhs 
       , const boost::_bi::bind_t<R, F, L>& rhs) 
{ 
    std::cout << lhs.compare(rhs) << std::endl; 
} 

template<typename T> 
void compare(T lhs, T rhs) 
{ 
    std::cout << (lhs == rhs) << std::endl; 
} 

void func(int) {} 

int main() 
{ 
    compare(boost::bind(func, 1), boost::bind(func, 1)); 
}