einstein
einstein

Reputation: 13850

Returning a struct with a function member that refer to a variable in parent scope

I'm trying to implement a function that returns a struct with a member function that refer to a variable in parent scope.

struct Scanner {
  int nextToken();
}

Scanner test() {
  token = 1;
  return {
    int nextToken() {
      return token;
    }
  };
}

I don't know if this is doable in C++. I'm a JavaScript developer and I don't know how to accomplish this. Are there any suggestion on how to refer to the variable token and return a struct or class that can provide a function nextToken()?

Upvotes: 1

Views: 74

Answers (1)

Mario
Mario

Reputation: 36487

You can't do it in older versions of the C++ standard (at least not as easy).

The far better (and easier) approach would be using C++11's lambdas.

Something like this (untested right now and most likely includes some syntax problem or other mistake somewhere):

struct Scanner {
    std::function<int()> nextToken;
};

Scanner test() {
    token = 1;
    return {
        [=](){ return token; }
    };
}

However, are you really sure you'll need to do it this way? This seems like a perfect use case for simple/classic class inheritance (which is possible with structs as well):

struct Scanner {
    virtual int nextToken() { return 0; }
}

struct TestScanner : public Scanner {
    virtual int nextToken() { return 1; }
}

Upvotes: 2

Related Questions