How can I rewrite this javascript code to C++11?

2019-03-31 14:31发布

问题:

This is the javascript closure code I saw at Javascript Definitive Guide. I'd like to write it as C++11

var uniqueID1 = (function()
{
    var id = 0;
    return function() { return id++; };
})();    

This is the cpp code I wrote. But it isn't be compiled. Can C++11 represent the same expression?

auto c = []() -> int (*)() { int x = 0; return [&x]() -> int { return x++; }};

I'm using VS2010

Edit: This is the full javascript sample code I made. You can test easily how the code works at your web browser.

<head>
<script language="javascript">
var uniqueID1 = (function()
{
    var id = 0;
    return function() { return id++; };
})();

var uniqueID2 = (function()
{
      var id = 0;
      return function() { return id++; };
})();
</script>
</head>

<body>
        <input value = "uniqueid1" type="button" OnClick="alert(uniqueID1());"></input>
        <input value = "uniqueid2" type="button" OnClick="alert(uniqueID2());"></input>
</body>
</html>

回答1:

OK, first let's break down what your JavaScript does.

function()
{
    var id = 0;
    return function() { return id++; };
}

This creates a function. A function with no name, which takes no parameters. This function, when called, will return a new function. The inner function will have access to a locally scoped variable, and this variable will be part of the state of that inner function.

Each time this function is called, it will return a new function. That new function will have its own state (var id = 0; has to do something, after all). Each call of the outer function will return a new function with new state.

This:

(function()
{
    var id = 0;
    return function() { return id++; };
})

Wraps the function in a pair of parenthesis. This is needed for operator precedence rules, to allow this to work:

(function()
{
    var id = 0;
    return function() { return id++; };
})()

This creates a function, and then calls the function. That's what the last () do at the end. It calls the outer function, which creates an inner function with its own scope and returns it.

In this expression, the outer function is lost. It's gone; you can't access it anymore. You created it for just long enough to call it, then let it drop into the trashcan of garbage collection.

Given all of this, we can see that this statement:

var uniqueID1 = (function()
{
    var id = 0;
    return function() { return id++; };
})();

Creates the outer function, calls the function which returns a new function, and then stores the inner function in a variable called uniqueID1.

If you need proof that this is true, try this in your HTML:

var uniqueMaker = function()
{
    var id = 0;
    return function() { return id++; };
};

var uniqueID1 = uniqueMaker();
var uniqueID2 = uniqueMaker();

You'll get the same answer as your copy-and-paste version.

If we want C++ code to mimic this, we need to perform each step with proper C++ code.

First, the inner function. In C++, lexical scoping does not exist. So you cannot return functions that reference variables in other scopes. You can only return a lambda that has a copy of variables from another scope. Also, lambdas cannot modify scope unless you explicitly allow it. Thus, the inner code must look like this:

int id = 0;
return [=]() mutable { return ++id; };

That's all well and good, but now we need to create a lambda that will return this stateful lambda function. In C++, functions that have state are not the same as function pointers. And since the type of a lambda is compiler-defined, there's no way to type its name. Therefore, we must employ std::function as the return type of the outer function.

[]() -> std::function<int()>
{
  int x = 0;
  return [=]() mutable { return x++; };
}

This creates a lambda function that, when called, will return an inner function with its own state. State that is independent from any subsequent calls to this function. Just like the JavaScript example.

Now, that's not enough. Remember, your JavaScript creates the outer function, calls it, and stores only its return value. The outer function itself is discarded. So we need to mimic this. Fortunately, this is easy enough in C++; it looks just like JavaScript:

([]() -> std::function<int()>
{
  int x = 0;
  return [=]() mutable { return x++; };
})()

Lastly, we stick it in a variable:

auto uniqueID1 = ([]() -> std::function<int()>
{
  int x = 0;
  return [=]() mutable { return x++; };
})();

The type of uniqueID1 will be std::function<int()>. It won't be the type of the outer function. The outer function is just a temporary that was used to create the inner scope.



回答2:

I assume you're not asking for a literal translation, but rather how to best express this construct in C++. Your JavaScript construct is in some sense "faking a constructor", and your ID generator is best expressed as a simple class in C++. Then you just make instances of that class:

class UniqueID
{
    unsigned int value;
public:
    UniqueID() : value(0) { }
    unsigned int operator()() { return ++value; }
};

Usage:

UniqueID gen1, gen2;

some_function(gen1());
another_function(gen2());
Foo x(Blue, "Jim", gen1());

This approach is lighter-weight than a std::function wrapper, although a straight-up lambda will produce a similar data structure (though you cannot know its type name). You can initialize value to -1 if you want the first ID to be 0 (though it might be useful to reserve 0 as a special value).