【问题标题】:boost::bind with templated functorsboost::bind 与模板化函子
【发布时间】:2014-10-20 22:21:46
【问题描述】:

只是试图让这个简单的测试用于访问函数运算符。我已经研究了 boost::bind (尤其是 overloaded section ),但还没有找到让它工作的方法。

#include <iostream>

#include <boost/bind.hpp>

template <typename FooType>
struct Foo {
    const FooType tmp_value;

    Foo(const FooType& tmp_) :
    tmp_value(tmp_)
  {
  }

    template<typename Object>
  void operator()(Object& operand)
  {
    std::cout << operand << std::endl;
    operand += tmp_value;
  }
};

int main() {


    double t = 4.0;
    Foo<double> e(1.0);
    std::cout << t << std::endl;
    e(t);   // Works
    std::cout << t << std::endl; 

    double d = 5.0;
    Foo<double> p(1.0);
    auto f1 = boost::bind(&Foo::operator(), p, _1); // Blows up at compile

    std::cout << d << std::endl;
    f1(d); 
    std::cout << d << std::endl;

}

编译器输出:

g++ -Wall --std=c++0x -I.  bind.cc -o binder
bind.cc:33:25: error: expected a class or namespace
    auto f1 = boost::bind(&Foo::operator(), p, _1); // Blows up at compile
                           ^

我知道我只是缺少一些简单的东西,任何帮助都会很棒。

【问题讨论】:

  • 您不能获取模板的地址(并且您正在使用 Foo 而不指定模板参数)。无论如何,你有一个函子,直接绑定函子就行了。
  • 需要模板运算符方法吗?如果您在哪里使用 Foo 类型名,例如 void operator()(const FooType&amp; operand),那么 boost::bind&lt;&amp;Foo&lt;double&gt;::operator(), p, _1); 将起作用,并且还应该有助于确保您不会尝试对不兼容的类型执行复合赋值。

标签: c++ c++11 boost functor boost-bind


【解决方案1】:

您试图在不指定类型参数的情况下获取成员函数模板的地址,这是不可能的。如果您为 Foooperator() 添加类型参数,您的代码就可以工作。

auto f1 = boost::bind(&Foo<double>::operator()<double>, p, _1);
//                        ^^^^^^^^            ^^^^^^^^

但是,作为 T.C.在 cmets 中说,你已经有一个函子,可以直接绑定为

auto f1 = boost::bind<void>(p, _1); // void is the return type of operator()

Live demo

【讨论】:

    【解决方案2】:

    正如评论中所述,您可以绑定p,因为它已经是一个仿函数。是的,它将作为模板以多态方式运行。

    但是,根据编译器/增强版本,默认情况下您可能无法获得 decltype() goodness,您必须添加

    typedef void result_type;
    

    Foo函子类:Live On Coliru

    或者,您可以#define BOOST_RESULT_OF_USE_DECLTYPE 在包含任何提升标头之前。

    【讨论】:

      猜你喜欢
      • 2012-07-04
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多