0

I'm writing a (my own language) to C++ transpiler. I'd like to be able to offer a kind of virtual sub function that is transpiled into being part of the C++ code in the same scope in which it is called.

Here is an example of the type of C++ code I'd want to generate:

if (a == {if (getValue(d) == 5) { long r = next(); next(); return r; } else return 0;})
dosomething();

It says if a is equal to the result of what's in the brackets, then dosomething().

You can see the idea is to inline a function within an expression. Yes that could be done by allowing the compiler to inline, but in this case I want to keep access to the variables in the outer scope, which I would lose if it actually were another function.

Any decent way to do this?

Alasdair
  • 11,936
  • 14
  • 66
  • 125

1 Answers1

4

If I correctly get what you are doing, you can simply use lambda expression here. This of course requires C++11

if (a ==
   [&] () {
        if (getValue(d) == 5) { 
            long r = next();
            next(); 
            return r;
        } else { 
            return 0;
        } 
    }()) {
    dosomething();
}

If you are writing translator/transpiler you may want to try more explicit capture list than this generic [&].

bartop
  • 8,927
  • 1
  • 18
  • 46