【问题标题】:omit std::placeholders in std::bind在 std::bind 中省略 std::placeholders
【发布时间】:2016-07-31 05:04:28
【问题描述】:

要创建 std::function,我要做的是:-

std::function<void(int,int,int)> f=
    std::bind(&B::fb,this,
        std::placeholders::_1,
        std::placeholders::_2,
        std::placeholders::_3
    );  

void B::fb(int x,int k,int j){} //example

很明显B::fb接收三个参数。
为了提高可读性和可维护性,我希望我可以改为:-

std::function<void(int,int,int)> f=std::bind(&B::fb,this);  //omit _1 _2 _3

问题
C++ 中是否有任何功能可以省略占位符?
它应该自动按顺序调用_1,_2,...。

我用谷歌搜索了“省略占位符 c++”,但没有找到任何线索。

【问题讨论】:

  • 您不能省略占位符。请记住,B::fb 可能会过载。
  • 然后,让它向我抛出“模棱两可”的编译错误。
  • 好吧,如果你省略了paceholders,它现在确实会抛出一个错误。不是“模棱两可”,但足够接近。
  • 您知道B::fb 没有重载,但语言规范不知道这一点。有一些回顾论文正在朝着标准化的方向努力。您可能需要等待才能解决此问题。
  • @KayEss B::fb 也可以用相同数量的参数重载,在这种情况下编译器会产生错误。

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


【解决方案1】:

您可以创建函数助手(那些是 C++14):

template <class C, typename Ret, typename ... Ts>
std::function<Ret(Ts...)> bind_this(C* c, Ret (C::*m)(Ts...))
{
    return [=](auto&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };
}

template <class C, typename Ret, typename ... Ts>
std::function<Ret(Ts...)> bind_this(const C* c, Ret (C::*m)(Ts...) const)
{
    return [=](auto&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };
}

然后就写

std::function<void(int, int, int)> f = bind_this(this, &B::fb);

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多