首页 > 解决方案 > Specification of lambda's return value doesn't work

问题描述

I've got a problem. The funciton "__sub" parses a string like "1x + (5y - 2)". Each time it sees "(", it calls itself to parse exactly what is in parenthesis. Here is some pseudocode, illustrating the problem:

auto __sub = [&needed_fn](const char *& iter, char end_at) -> int {
  for (; *iter != end_at; iter++) {
    if () {
      int number = needed_fn(iter);
    } else if (*iter == '(') {
      int sub_result = __sub(iter, ')');
    }
  }
  return 0; // temporarily, as for debugging purposes only needed
};

But this doesn't work. At first there was no specification of (-> int). And it doesn't work in both cases with or without that specification of the return value.

It says:

a.cpp: In lambda function:
a.cpp:97:22: error: use of ‘__sub’ before deduction of ‘auto’
 int sub_result = __sub(it, ')');

标签: c++recursionlambdareturn-valueauto

解决方案


Suggestion: define __sub as a std::function<int(const char *, char)>

std::function<int(const char * &, char)> __sub;

__sub = [&needed_fn](const char *& iter, char end_at) -> int {
  for (; *iter != end_at; iter++) {
    if ( /* ??? */ ) {
      int number = needed_fn(iter);
    } else if (*iter == '(') {
      int sub_result = __sub(iter, ')');
    }
  return 0;
};

otherwise the compiler can't deduce (auto) the type of __sub() using the same __sub() inside the body of __sub().


推荐阅读