c++ - 扩展包含 lambda 类型的参数包时出现奇怪的错误
问题描述
我有一个函数,foo
如下例所示:
template <typename... Parameters>
void foo(std::function<void (Parameters &)>... functions) {
// does interesting things with these functions
}
现在我想用一些 lambdas 调用这个函数,例如:
foo([](const std::string & string) {});
不幸的是,这不起作用,因为我收到以下错误:
error: no matching function for call to 'foo'
note: candidate template ignored: could not match 'function<void (type-parameter-0-0 &)>' against '(lambda at file.cpp:50:23)'
AFAIK,也就是说,因为 lambdas 不能被隐式转换为std::functions
那样。
解决此问题的一种方法是std::function
像这样手动包装 lambda:
foo(std::function<void (const std::string &)>([](const auto & string) {}));
但是对于多个 lambda,这将变得非常乏味。
为了解决这个问题,我尝试创建一个包装函数,该函数检测使用辅助类型传递的 lambda 的参数类型,然后将 lambda 包装为正确的std::function
类型。这是仅用于单个参数(即不是可变参数)的包装函数:
template <typename Function>
void fooWrapped(Function && function) {
foo(std::function<void (typename FunctionTypeTraits<Function>::ParameterType &)>(function));
}
辅助类型FunctionTypeTraits
是这样实现的:
template <typename Function>
class FunctionTypeTraits:
public FunctionTypeTraits<decltype(&std::remove_reference<Function>::type::operator())> {};
template <typename Param>
class FunctionTypeTraits<void (&)(Param &)> {
typedef Param ParameterType;
};
现在我可以用我的 lambda 调用包装函数,编译器非常高兴:
fooWrapped([](const std::string & string) {});
原则上,我现在应该能够fooWrapper
像这样制作可变参数:
template <typename... Functions>
void fooWrapped(Functions &&... functions) {
foo((std::function<void (typename FunctionTypeTraits<Functions>::ParameterType &)>(functions))...);
}
然而,这不起作用。如果我用完全相同的代码调用这个新函数,我会收到以下错误:
error: 'std::remove_reference<void ((lambda at file.cpp:50:23)::*)(const std::string &) const>::type' (aka 'void ((lambda at file.cpp:50:23)::*)(const std::string &) const') is not a class, namespace, or enumeration
我不太明白这个错误。为什么相同的方法适用于单个模板类型,但不适用于扩展的参数包?这可能只是一个编译器错误吗?
还有另一种方法,我可以实现foo
使用 lambdas 调用的目标,而无需手动将它们中的每一个包装在std::function
?
解决方案
lambda 的地址类型operator()
不是,你需要定义你的基本情况void (Lambda::*)(Param&) const
为:void (&)(Param &)
FunctionTypeTraits
template <typename Function>
struct FunctionTypeTraits:
public FunctionTypeTraits<decltype(&std::remove_reference<Function>::type::operator())> {};
template <typename Lambda, typename Param>
struct FunctionTypeTraits<void (Lambda::*)(Param) const> {
typedef Param ParameterType;
};
另一点是,在您fooWrapped
的 中,指定的类型std::function
应该是void (typename FunctionTypeTraits<Function>::ParameterType)
,而不仅仅是ParameterType
因为后者不是函数类型:
template <typename... Function>
void fooWrapped(Function&&... function) {
foo(std::function<void (typename FunctionTypeTraits<Function>::ParameterType)>(function)...);
}
推荐阅读
- csv - 如何在 DataStage 中插入带引号的值?
- php - 如何使用嵌套的 if / else 语句(表单检查)
- swiftui - SwiftUI GeometryReader 不会在中心布局自定义子视图
- c# - UWP 程序与 Winforms 的功能不同
- angular - 如何在尤里卡服务器上注册角度应用程序
- python - Cython 无法导入和执行函数:存储临时 Python 参考的不安全 C 派生
- linq - 查询动态组织服务上下文'从范围引用..'linq异常
- javascript - 从功能区双击加载 TaskPane 会中断功能,这会阻止 TaskPane 下次显示
- python - 我的引导导航栏显示不正确:
- excel - 在 If 语句中使用 IsError