【问题标题】:std::bind function taking std::unique_ptr as argument以 std::unique_ptr 作为参数的 std::bind 函数
【发布时间】:2017-05-28 09:36:18
【问题描述】:

请帮我解决我面临的绑定问题...

我有一个类成员方法:

std::unique_ptr<TopoDS_Shape> test( std::unique_ptr<TopoDS_Shape> Shape ) const
{
    std::unique_ptr<TopoDS_Shape> Result = std::make_unique<TopoDS_Shape>();
    return( std::move( Result ) );
}

我需要从中构造一个std::function 指针。为此,我需要使用std::bind 来转发这个指针,因为test(...) 是一个类成员方法:

std::function<std::unique_ptr<TopoDS_Shape>(std::unique_ptr<TopoDS_Shape>)> tTestFunction;

tTestFunction = std::bind( &ComponentModelModifier::test, this, std::placeholders::_1 );

然后,std::function 指针在我的线程池添加方法中使用这个签名:

template<typename FUNCTION, typename... ARGUMENTS>
auto ThreadPool::add( FUNCTION&& Function, ARGUMENTS&&... Arguments ) -> std::future<typename std::result_of<FUNCTION(ARGUMENTS...)>::type>

电话:

std::unique_ptr<TopoDS_Shape> tShape = std::make_unique<TopoDS_Shape>();

ThreadPool tp;
std::future<std::unique_ptr<TopoDS_Shape>> ResultFuture = tp.add( tTestFunction, std::move( tShape ) );

但是构建总是失败:

error: no type named ‘type’ in ‘class std::result_of<std::reference_wrapper<std::_Bind<std::function<std::unique_ptr<TopoDS_Shape>(std::unique_ptr<TopoDS_Shape>)>(std::unique_ptr<TopoDS_Shape>)> >()>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;

我知道 std::unique_ptr 不是可复制构造的。这就是为什么我尝试使用 std::move 但没有任何效果......

如果有任何帮助或朝着正确的方向发展,我会很高兴。提前致谢!马丁

【问题讨论】:

  • 您的函数是否确实接受std::unique_ptr&lt;TopoDS_Shape&gt; Shape 按值
  • 我说是的。该函数应该超越用作参数的唯一指针的所有权。我希望你 ment test()...
  • 这是你的真实代码吗? reference_wrapper 是从哪里来的?
  • 是的。我做了一点跟踪,似乎std::reference_wrapper 来自std::result_of,正如auto ThreadPool::add( FUNCTION&amp;&amp; Function, ARGUMENTS&amp;&amp;... Arguments ) -&gt; std::future&lt;typename std::result_of&lt;FUNCTION(ARGUMENTS...)&gt;::type&gt;中使用的那样
  • 你能给我们看一个实际的minimal reproducible example而不是小sn-ps吗?

标签: c++ binding c++14 move unique-ptr


【解决方案1】:

我的线程池的add()方法好像没有成功推导出参数类型,所以报了上面的错误信息。我试图在我的函数调用中更加具体——尤其是在std::move 中,我试图指定结果类型。我还需要修改test() 方法签名以使用共享指针(请参阅参数类型)。请参阅下面的代码:

std::unique_ptr<TopoDS_Shape> test( const std::shared_ptr<TopoDS_Shape> Shape ) const
{
    std::unique_ptr<TopoDS_Shape> Result = std::make_unique<TopoDS_Shape>();
    return( std::move( Result ) );
}

...

std::future<std::unique_ptr<TopoDS_Shape>> ResultFuture = tp.add( tTestFunction, std::move<std::shared_ptr<TopoDS_Shape>>( tShape ) );

然后我就可以编译代码了……目前还不清楚为什么std::unique_ptr 不能用作test() 方法参数类型,但至少我有一个可行的解决方案。 也许它与 std::function 的使用有关,它必须具有所有参数可复制构造,std::unique_ptr 的情况并非如此。我不知道如何在这里调用移动构造函数而不是删除副本。 如果有人有想法,请发表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 2016-03-31
    • 2016-03-21
    相关资源
    最近更新 更多