改变 return 类型的 lambda

Mutate return type of a lambda

不幸的是,这个问题的完整背景太复杂了,无法解释,但足以说明它涉及一些复杂的模板元编程,我发现自己不得不做一些有趣的事情。我试图将我遇到的一个问题归结为一个最小的例子,所以这个问题可能看起来很尴尬。如果可以做到这一点,我很想知道怎么做,如果不能,我很想听听可能的替代方案。

我想创建一个函数,将 lambda 函数作为输入,该函数可能 return void 或其他。如果它确实 return void,我想将它转换成一个相同的 lambda,而不是 returning void,returns true.

template <typename InputFuncType>
auto function_converter(InputFuncType lambda_func)
{
  // I also need to figure out how to deduce the return type of lambda_func
  // might be something like this.
  if constexpr (std::is_same<std::result_of<InputFuncType>::type, void>::value)
  {
    // Current best guess. Note that in the context of the converter, I don't explicitly know
    // lambda_func's input type, so I'm not sure how to do something like this.
    return [](InputFuncType::input_args_t... args) {lambda_func(args); return true;};
  }
  return lambda_func;
}

// target usage
const auto lam1 = [](int a) {return;};
const auto lam2 = function_converter(lam1);

int x = 4;
lam1(x);  // returns void
const bool y2 = lam2(x);  // returns true

我正在使用 c++17。

我想有点多余,但下面的包装器应该可以工作

template <typename InputFuncType>
auto function_converter (InputFuncType lf)
 {
   return [=](auto && ... args)
    {
      using RT = decltype(lf(std::forward<decltype(args)>(args)...));

      if constexpr ( true == std::is_same_v<void, RT> )
       {
         lf(std::forward<decltype(args)>(args)...);

         return true;
       }
      else
         return lf(std::forward<decltype(args)>(args)...);
    };
 }

基本上,这个想法是在内部 lambda 中传递关于返回类型的检查。