我正在像这样修改 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/