简体   繁体   English

如何使用可变数量的参数重载 lambda 函数?

[英]How can I overload a lambda function with a variadic number of parameters?

I'm using the solution proposed in this answer to get the arguments from a lambda function and it's working fine when the number of parameters is fixed.我正在使用此答案中提出的解决方案从 lambda 函数中获取参数,并且在固定参数数量时它工作正常。 I first created a variant with one argument and would like to add a second one which accepts two arguments.我首先创建了一个带有一个参数的变体,并想添加第二个接受两个参数的变体。 I'm not looking to generalize this, just the two options below.我不打算概括这一点,只是下面的两个选项。

class MyClass {
  template<typename Lambda>
  typename std::enable_if<function_traits<Lambda>::arity, 1>>
  void Each(Lambda lambda) {
    using Traits = function_traits<decltype(lambda)>;
    using Arg0 = typename Traits::template arg<0>::type;
    lambda(Conv<Arg0>().ToType(this));
  }

  template<typename Lambda>
  typename std::enable_if<function_traits<Lambda>::arity, 2>>
  void Each(Lambda lambda) {
    using Traits = function_traits<decltype(lambda)>;
    using Arg0 = typename Traits::template arg<0>::type;
    using Arg1 = typename Traits::template arg<1>::type;
    lambda(Conv<Arg0>().ToType(this), Conv<Arg1>().ToType(this));
  }
}

void main() {
  MyClass myClass;
  myClass.Each([](int arg) {});
  myClass.Each([](int arg0, int arg1) {});
}

This code, of course, doesn't compile at all but I still don't understand how enable_if works well.当然,这段代码根本无法编译,但我仍然不明白 enable_if 是如何运作良好的。 I'm using GCC 6.2.0 so can't use C++17 features like if constexpr, otherwise I'd be using that.我使用的是 GCC 6.2.0,所以不能使用 C++17 特性,比如 if constexpr,否则我会使用它。 What does the correct implementation look like here?这里的正确实现是什么样的?

Assuming Conv is defined假设Conv已定义


class MyClass {
  public:

  template<typename Lambda>
  typename std::enable_if<(function_traits<Lambda>::arity == 1), void>::type
  Each(Lambda lambda) {
    using Traits = function_traits<decltype(lambda)>;
    using Arg0 = typename Traits::template arg<0>::type;
    lambda(Conv<Arg0>().ToType(this));
  }

  template<typename Lambda>
  typename std::enable_if<(function_traits<Lambda>::arity == 2), void>::type
  Each(Lambda lambda) {
    using Traits = function_traits<decltype(lambda)>;
    using Arg0 = typename Traits::template arg<0>::type;
    using Arg1 = typename Traits::template arg<1>::type;
    lambda(Conv<Arg0>().ToType(this), Conv<Arg1>().ToType(this));
  }
};

int main() {
  MyClass myClass;
  myClass.Each([](int arg) {});
  myClass.Each([](int arg0, int arg1) {});
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM