【问题标题】:Template overloading (diff. number of arguments)模板重载(不同的参数数量)
【发布时间】:2011-07-31 06:15:50
【问题描述】:

我想创建您在下面看到的这些函数模板。他们的目的是比较函子,但我需要介绍 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 类型的那个,一切都会正常工作。

如何让它选择正确的函数模板来使用?

【问题讨论】:

  • 看起来您依赖的类型是 boost 实现私有类型。您确定您传入的类型完全正确吗?如果使用第一个模板需要任何类型的隐式转换,则首选第二个模板,因为它可以使用原始类型进行实例化,因此是更好的匹配。
  • 我首先做了int i = boost::bind(func, 1) 让编译器告诉我绑定返回什么。此外,function_equal templates 也将 bind_t 作为参数,所以我也应该这样做是安全的。
  • 刚刚查找 boost::bind 并按值返回其参数,因此 compare(boost::find(func, 1), boost::bind(func, 1)) 不应使用第一个模板,因为您无法将临时绑定到非常量引用。如果您将const 添加到第一个,那么它应该没问题。至于如果您注释掉更通用的模板,为什么它会起作用,我不太确定。在我的实现中,实例化通用模板时确实会出现错误。
  • @Charles 是的,它有效。将其添加为答案,以便我接受。 :)

标签: c++ templates boost-bind


【解决方案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) );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多