c++ - 是否可以重新路由 lambda 以将其包装在包装类中?

标签 c++ visual-studio-2012 c++11

我正在像这样修改 std::function 的 vector :

#include "stdafx.h"
#include <stdexcept>
#include <functional>

#include <iostream>
#include <vector>

typedef std::function<void(int)> FuncType;

std::vector<FuncType> container;

int _tmain(int argc, _TCHAR* argv[])
{

    container.push_back([](int i){std::cout << i+1 << std::endl;});
    container.push_back([](int i){std::cout << i+42 << std::endl;});

    for(auto & o : container)
    {
        o(4);
    }

    return 0;
}

基本上只返回 5 和 46,我在考虑是否可以将容器的声明更改为某种包装类,但要保持 lambda 的后推(= 除了声明之外不更改任何其他内容)。

目前我试图实现一些 stub 包装器,什么都不做,应该只编译,但似乎不能隐式地完成从 lambda 到包装器的转换。

#include "stdafx.h"
#include <stdexcept>
#include <functional>

#include <iostream>
#include <vector>


typedef std::function<void(int)> FuncType;
template<class T>
class Wrapper
{
public:
    Wrapper(T t)
    {
        _t = t;
    }

   void operator()(int i) const
   {
       _t(i);
   }

protected:

   T & _t;

};


std::vector<Wrapper<FuncType>> container; // Only line changed

int _tmain(int argc, _TCHAR* argv[])
{

    container.push_back([](int i){std::cout << i+1 << std::endl;});
    container.push_back([](int i){std::cout << i+42 << std::endl;});

    for(auto & o : container)
    {
        o(4);
    }

    return 0;
}

这里的目标是将调用包装到 o(int) 并输出一些诊断信息,例如 o.target_type().name() 或性能值等,但没有将 push_back 更改为包装容器(也避免宏魔法)

注意:由于我使用的是 VS 2012,可变参数模板参数尚未实现,因此标准 MS std::function 求助于一些宏魔术,如 _VARIADIC_EXPAND_P1_1(_CLASS_FUNC_CLASS_1, , , , ) 到提供程序 operator()

最佳答案

您正在尝试进行两个用户定义的转换,这在 C++ 中是非法的。相反,使构造函数成为受约束的模板。见下文:

#include <functional>
#include <utility>
#include <iostream>
#include <vector>
#include <type_traits>

typedef std::function<void(int)> FuncType;

template<class T>
class Wrapper
{
public:
    template<typename U,
    typename std::enable_if<
        std::is_constructible<T, U>::value,
        int
    >::type = 0>
    Wrapper(U t)
      : _t(std::move(t))
    {}

   void operator()(int i) const
   {
       _t(i);
   }

private:
   T _t;
};

std::vector<Wrapper<FuncType>> container; // Only line changed

int main(int argc, char* argv[])
{
    container.push_back([](int i){std::cout << i+1 << std::endl;});
    container.push_back([](int i){std::cout << i+42 << std::endl;});

    for(auto & o : container)
    {
    o(4);
    }
}

关于c++ - 是否可以重新路由 lambda 以将其包装在包装类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24382226/

相关文章:

c++ - boost::asio 数据包顺序和连续性

c# - 托管函数在非托管结构(C++、C#)中作为回调函数传递的问题

android - 如何将最新的 c++ protobuf (3.2) 与 Android NDK 集成/安装?

c# - 为 .NET 4 和 .NET 4.5 构建整个解决方案并将文件复制到特定文件夹

c++ - makefile 链接不起作用(尽管没有错误消息)

c++ - Microsoft Visual Studios 2012 无法打开 "python33.lib"

visual-studio-2012 - NuGet;无法将包作为 Visual Studio 2012 中报告的错误版本

c++ - 将 vector 传递给某些需要某种大小的数组引用的遗留 API 的任何方法

c++ - 为什么我可以使用 operator= 而不是 operator== 与 C++11 大括号初始化器?

C++转义控制字符