【问题标题】:How to do this with std::bind?如何用 std::bind 做到这一点?
【发布时间】:2012-12-12 07:20:05
【问题描述】:

(注意: 从标签中应该已经清楚,这是严格的 C++03. 是的,我知道,lambda 让所有这些痛苦都消失了(我敢打赌并带来了新的种类),但这是一个嵌入式系统,具有 90 年代的操作系统版本,并且有人告诉我,我应该很高兴我有一个 C++03 编译器(GCC4.1.x,BTW),或者是一个 C++ 编译器。所以请不要发布 C++11 解决方案。不需要磨合,真的。
另外,std::bind()std::function() 等当然是在std::tr1 中,但我删除了tr1 前缀,因为我认为它主要只会给代码添加噪音。
)

我有一些类似服务器的东西需要注册函数,我需要调整它们以调用一些对象的相似但略有不同的函数。这些函数有不同的参数列表。服务器“知道”并且当我尝试注册一个函数时,它只接受一个具有正确签名的函数(即,与std::function 要求一样正确),这取决于作为模板参数传入的一些魔术标签。

这是代码的草图

// this I just use
class server {
public:
    template<unsigned int MagicTag>
    bool register_call(typename some_traits_type<MagicTag>::func_type);
};

// this needs to be called from the server
class X {
public:
    bool foo();
    bool bar(std::string&);
    bool baz(int);
};

// this is the glue
class Y {
public:
    Y(X& x) : x_(x) {
        register_call<MAGIC_FOO>(&Y::foo    );
        register_call<MAGIC_BAZ>(&Y::bar, _1);
        register_call<MAGIC_FBZ>(&Y::baz, _1);
    }

private:
    X&                    x_;

    template<unsigned int MagicTag, typename Function>
    bool register_call(Function function) {
        somewhere->register_call<MagicTag>(std::bind( function
                                                    , this ));
    }
    template<unsigned int MagicTag, typename Function, typename PlaceHolder1>
    bool register_call(Function function, PlaceHolder1 place_holder1) {
        somewhere->register_call<MagicTag>(std::bind( function
                                                    , this
                                                    , place_holder1 ));
    }

    int foo()               {return x_.foo()  ? MAGIC_OK : MAGIC_FAILED;}
    int bar(std::string& s) {return x_.bar(s) ? MAGIC_OK : MAGIC_FAILED;}
    int baz(int i)          {return x_.baz(i) ? MAGIC_OK : MAGIC_FAILED;}
};

这确实有效,但实际上还有更多的功能,而且这样做是一种乏味的复制粘贴工作,这侮辱了我的尊严感并产生了臭代码。由于所有这些函数的作用完全相同,唯一的区别是它们调用的函数以及它们具有或不具有传递的参数,我应该能够将它们折叠成一个参数化函数,隐藏@987654330 背后的差异@。如果做不到这一点,我决定首先对所有没有任何参数的函数执行此操作(如foo()),这是绝大多数。

所以我想通过一个函数Y::call_it 来路由X 中所有类似foo() 的函数的调用,该函数完成了繁琐的部分:

int call_it(std::function<bool()> f) {return f() ? MAGIC_OK : MAGIC_FAILED;}

并将X中的适当函数绑定为它的参数:

register_call<MAGIC_FOO>(&X::foo); // note the X!

// (this is wrong)
somewhere->register_call<MagicCode>( std::bind( std::bind( &Y::call_it
                                                         , this
                                                         , function )
                                              , std::ref(x_) );

显然,这是错误的,我解决此问题的所有其他尝试也是如此。 (我现在才玩std::bind() 10 周,所以请多多包涵)。最后,我在std::function 模板化的胆量中迷失了令人难以置信的搞笑错误消息迷宫,这会让一个成年人流泪,并且应该至少养活一个心理医生和他的大家庭一年。

所以在我 kill myself out of sheer frustration 和我的孩子成为孤儿之前 - 我该怎么做?

【问题讨论】:

  • 我从未使用过 std::bind。怎么样才算是告白。但是你不想register_call&lt;MagicCode&gt;(std::bind(&amp;Y::call_it, this, std::bind(ptmf, std::ref(x_))); 吗?
  • @rici:是的,当然,你是对的。 I have already seen this myself 很简单,我已经把头撞在墙上好几个小时了,这只是第 1001 次尝试让它工作时的困惑状态,那时我决定我需要问对这个。然而,问题是我也无法让它以另一种方式工作。 叹息。
  • 我想这就是我从未使用过 std::bind 的原因。模板元调试很疯狂。或者它让你发疯。这可能就是所有标准库实现都不符合标准的原因。祝你好运!
  • @rici:正如我所说,我是 10 月中旬才开始使用的,到目前为止,我喜欢它。我在C++ room 中得到了很多帮助,但总的来说,它是一个很好的工具箱,除非他们给我真正的 lambda 函数,否则我不想回馈它。 :)

标签: c++ c++03 std-function stdbind


【解决方案1】:

据我所知,您想调用 Y::call_it() 并适当绑定 std::function 对象。鉴于您的内部函数采用不同数量的参数,因此有必要为传递其他参数的情况创建一个std::function&lt;bool()&gt; 生成器。假设X 对象可以在注册时绑定,那么无需额外参数即可直接注册成员函数:

template <int Magic, typename RC>
void register_call(RC (X::*member)()) {
    somewhere->register_call<Magic>(
        std::bind(&Y::call_it, this,
             std::function<bool()>(std::bind(member,
                                             std::ref(this->x_)))));
}

当传递一个或多个参数时,需要在调用时创建一个std::function&lt;bool()&gt; 对象,因为需要绑定额外的参数。我不认为这可以在没有辅助函数的情况下完成,但可以通过每个参数数量的一个辅助函数来完成:

template <typename RC, typename Arg0>
static std::function<bool()>
bind_argument(RC (X::*member)(Arg0), X& x, Arg0 const& arg0) {
    return std::bind(member, std::ref(x), arg0);
}
template <int Magic, typename RC,
          typename Arg0, typename PlaceHolder>
void register_call(RC (X::*member)(Arg0), PlaceHolder pc) {
    somewhere->register_call<Magic>(
        typename some_traits_type<Magic>::type(
            std::bind(&Y::call_it, this,
                      std::bind(&bind_argument<RC, Arg0>, member,
                                std::ref(this->x_), pc))));
}

辅助函数创建一个绑定了附加参数的函数。请注意,被绑定的函数被构造为与注册函数所期望的类型相同:这是必要的,例如,创建一个接受额外的、被忽略的参数的函数。

下面是我用来查看是否编译的测试程序。我手头没有带有 TR1 的 C++2003 编译器,而是使用 C++2011 编译器编译了代码。但是,我认为我没有使用任何 C++2011 扩展,而这些扩展在带有 TR1 的 C++2003 中不可用。

#include <functional>

enum {
    MAGIC_OK,
    MAGIC_FAILED,
    MAGIC_FOO,
    MAGIC_BAR,
    MAGIC_FBZ,
    MAGIC_BAZ
};

template <int> struct server_traits;
template <> struct server_traits<MAGIC_FOO> {
    typedef std::function<bool()> type;
};
template <> struct server_traits<MAGIC_BAR> {
    typedef std::function<bool(std::string&)> type;
};
template <> struct server_traits<MAGIC_FBZ> {
    typedef std::function<bool(long)> type;
};
template <> struct server_traits<MAGIC_BAZ> {
    typedef std::function<bool(std::string, long)> type;
};


// this I just use
class server {
public:
    template<unsigned int MagicTag>
    bool register_call(typename server_traits<MagicTag>::type) {
        return true;
    }
};

server  s;
server* somewhere = &s;

// this needs to be called from the server
class X {
public:
    bool foo() { return true; }
    bool bar(std::string&) { return true; }
    bool baz(int) { return true; }
};

// this is the glue
class Y {
public:
    Y(X& x) : x_(x) {
        register_call<MAGIC_FOO>(&X::foo    );
        register_call<MAGIC_BAR>(&X::bar, std::placeholders::_1);
        register_call<MAGIC_FBZ>(&X::baz, std::placeholders::_1);
        register_call<MAGIC_BAZ>(&X::baz, std::placeholders::_2);
    }

private:
    X& x_;

    int call_it(std::function<bool()> f) {
        return f() ? MAGIC_OK : MAGIC_FAILED;
    }

    template <int Magic, typename RC>
    void register_call(RC (X::*member)()) {
        somewhere->register_call<Magic>(
            std::bind(&Y::call_it, this,
                 std::function<bool()>(std::bind(member,
                                                 std::ref(this->x_)))));
    }
    template <typename RC, typename Arg0>
    static std::function<bool()>
    bind_argument(RC (X::*member)(Arg0), X& x, Arg0 const& arg0) {
        return std::bind(member, std::ref(x), arg0);
    }
    template <int Magic, typename RC,
              typename Arg0, typename PlaceHolder>
    void register_call(RC (X::*member)(Arg0), PlaceHolder pc) {
        somewhere->register_call<Magic>(
            typename server_traits<Magic>::type(
                std::bind(&Y::call_it, this,
                          std::bind(&bind_argument<RC, Arg0>, member,
                                    std::ref(this->x_), pc))));
    }
};

int main()
{
    X x;
    Y y(x);
}

【讨论】:

  • 谢谢,迪特玛!如果没有我已经发现in the chat 的演员表,那些对std::bind() 的调用不会很好地嵌套。但是,我仍在与编译器争论带参数的函数,所以您的解决方案确实非常受欢迎。
  • 很遗憾,我也无法编译您的代码。对于采用std::string&amp; 的函数,编译器会叫no matching function for call to 'bind(&lt;unresolved overloaded function type&gt;, bool (X::*&amp;)(std::string&amp;), std::reference_wrapper&lt;X&gt;, std::_Placeholder&lt;1&gt;&amp;)'。还有两个错误。它似乎对Arg0 const&amp; arg0 感到不安,它既不适合int,也不适合std::string&amp;
  • 它肯定会为我使用 gcc 编译器。由于似乎与我正在使用的 libcxx 版本有关的错误,尝试使用 clang 编译代码失败。但是,尝试更改bind_argument() 的声明以删除Arg0 参数上的const&amp;const&amp; 是我推导参数的尝试遗留下来的,Arg0 无论如何都是正确的类型.
  • 是的,我已经删除了const&amp;,但这只会导致其他错误,这对我来说同样令人困惑:invalid initialization of reference of type 'std::string&amp;' from expression of type 'std::tr1::_NullClass'cannot convert 'std::tr1::_NullClass' to 'int' in argument passing,再加上另外两个,都涉及可能我的 std tr1 库的元组类的 Nil 类型。
  • 这个问题比较麻烦,但最终我们是这样做的,所以我会接受你的回答。
【解决方案2】:

从聊天频道链接来看,您似乎已将问题归结为嵌套绑定无法编译的事实:

bind( &Y::call_it, this, bind( &X::foo, ref(x_) ) )

因为编译器无法推断出内部 bind() 的类型签名(在这种情况下为 function)。这可能会起作用:

bind( &Y::call_it, this, function<bool()>( bind( &X::foo, ref(x_) ) ) )

如果是这样,你会有类似的东西

template<unsigned int MagicTag, typename Function >
bool register_call(Function func) {
    somewhere->register_call<MagicTag>(
      bind( &Y::call_it, this, function<bool()>( bind( func, ref(x_)))));
}

虽然我觉得第二个模板参数可能不是必需的。关键思想是在两个 std::bind 之间放置一个 std::function。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2019-09-19
    • 2019-04-30
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多