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 类型的那个,一切都会正常工作。

我怎样才能让它选择正确的功能模板来使用?

4

1 回答 1

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) );
}
于 2011-07-31T06:46:09.407 回答