如何将不可复制的std :: function存储到容器中? [英] How to store non-copyable std::function into a container?

查看:101
本文介绍了如何将不可复制的std :: function存储到容器中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++ 11中的矢量或其他容器中存储回调.

I want to store callbacks in a vector or another container in C++11.

一种方法是存储std :: function的向量.这对于lambda或带有可复制参数的std :: bind效果很好.

One way to do so would be to store a vector of std::function. This works well for lambda or std::bind with copyable arguments.

但是,如果有一个不可复制的(仅可移动的)参数,由于从lambda/std :: bind内部类型到std :: function ...的转换,它将失败.

However, if there is one non copyable (movable only) argument, it will fail due to the conversion from the lambda/std::bind internal type to the std::function...

#include <vector>

class NonCopyable {
public:
    NonCopyable() = default;
    NonCopyable(const NonCopyable &) = delete;
    NonCopyable(NonCopyable &&) = default;
};

int main() {
    std::vector<std::function<void()>> callbacks;
    callbacks.emplace_back([] {});

    NonCopyable tmp;
    callbacks.emplace_back(std::bind([](const NonCopyable &) {}, std::move(tmp)));
    // When converting the object returned by std::bind to a std::function,
    // a copy of the arguments happen so this code cannot compile.
    return 0;
}

有没有办法将std :: bind参数移入std :: function而不是复制它们?

Is there a way to move std::bind arguments into the std::function instead of copying them?

推荐答案

std :: ref std :: cref 复制对象(请参见 http://en.cppreference.com/w/cpp/实用工具/功能/reference_wrapper ).

std::ref and std::cref are meant to be used in this cases to avoid copying the object (see http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper).

不确定我是否正确回答了您的问题,但这对我来说是正确的:

Not sure that I got your question right, but this compiles for me:

#include <vector>
#include <functional>

class NonCopyable {
public:
  NonCopyable() = default;
  NonCopyable(const NonCopyable &) = delete;
  NonCopyable(NonCopyable &&) = default;
};

int main() {
    std::vector<std::function<void()>> callbacks;
    callbacks.emplace_back([] {});

    NonCopyable tmp;
    auto fun = std::bind([](const NonCopyable &) {}, std::cref(tmp));
    callbacks.emplace_back(fun);

    return 0;
}

如评论中所述,请小心所引用变量的生命周期!

As mentioned in the comments, be careful about the life cycle of the referenced variable!

这篇关于如何将不可复制的std :: function存储到容器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆