Template overloading (diff. number of arguments)
I wanted to create these function templates you see below. Their purpose is to compare functors, but I needed to cover a special case for the boost.bind type of functors.
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::end开发者_如何学Gol;
}
template<typename T>
void compare(T lhs, T rhs)
{
std::cout << (lhs == rhs) << std::endl;
}
The problem is that when I do compare(boost::bind(func, 1), boost::bind(func, 1))
, the compiler tries to use the second template. If I comment out the second one, it will correctly use the one specialized for the boost.bind type and everything will work fine.
How can I make it choose the correct function template to use?
boost::bind
returns a value which can't be bound to a non-const
reference. Your better specialized template needs to take it's arguments by value or by const
reference otherwise it won't be considered in the call: compare( boost::bind(func, 1), boost::bind(func, 1) )
.
This test program compiles and works correctly on my platform.
#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) );
}
精彩评论