C++ 类型删除,用 std::function 捕获单个类的多个方法

标签 c++ c++11 type-erasure std-function

考虑以下代码,其中 std::function 被使用了 3 次以捕获一个类的方法:

struct some_expensive_to_copy_class
{
    void foo1(int) const { std::cout<<"foo1"<<std::endl; }
    void foo2(int) const { std::cout<<"foo2"<<std::endl; }
    void foo3(int) const { std::cout<<"foo3"<<std::endl; }
};

struct my_class
{
    template<typename C>
    auto getFunctions(C const& c)
    {
         f1 = [c](int i) { return c.foo1(i);};
         f2 = [c](int i) { return c.foo2(i);};
         f3 = [c](int i) { return c.foo3(i);};
    }

    std::function<void(int)> f1;
    std::function<void(int)> f2;
    std::function<void(int)> f3;
};

然而,这将执行类 some_expensive_to_copy_class 的三个拷贝,正如人们可以从名称中猜到的那样效率低下。

是否有只制作一份拷贝的解决方法?

为了强调这一点,我在这里对使用 std::function 的方法感兴趣,而不是 void 指针,也不是相应的基于继承的实现。

最佳答案

使用 shared_ptr 制作一个拷贝,并捕获它。

auto spc = std::make_shared<const C>(c); 
f1 = [spc](int i) { return spc->foo1(i); }
f2 = [spc](int i) { return spc->foo2(i); }
f3 = [spc](int i) { return spc->foo3(i); }

关于C++ 类型删除,用 std::function 捕获单个类的多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820217/

相关文章:

Oracle Java SE 8u20 JDK 中泛型静态方法调用的 Java 泛型不兼容类型编译错误

c# - 从C#到C++的编码字符串

c++ - 在 VC++ 中编译头文件时遇到问题

c++ - 在 cpp unordered_map 的自定义哈希函数中插入不起作用

c++ - 每个范围类型的模板特化

c++ - 使用 Win32 线程模型时,MinGW-w64 是否支持开箱即用的 std::thread?

c++ - 推导可变参数模板参数失败?

c++ - 模板函数中的输出 vector <T>

swift3 - swift : RxSwift's asObservable() method and type erasure

scala - 为什么 Scala 在第一种情况下会警告类型删除而不是第二种情况?