首页 > 解决方案 > 扩展包含 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?

标签: c++lambdatypetraitsparameter-pack

解决方案


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)...);
}

演示。


推荐阅读