Hacker News new | ask | show | jobs
by Sharlin 3809 days ago
Should be noted that this only works on a "statically typeable" subset of Python where every variable has a de facto static type inferred at the first assignment. For instance, the following valid Python code would output invalid C++:

  var = []
  var = 2
2 comments

Yes you would have to program in a subset of python. But type annotations are not always needed.

For the array I do a little hackery. You can define the array without an initial value in the container and I can guess the value type.

  arr = []
  arr.append(1)
it will spit out

  std::vector<decltype(1)> arr{};
  arr.push_back(1);
Well, you could always begin another scope with each assignment.

    auto var = // this type can't be inferred because it's not used
    {
      auto var = 2;
    }
I'm too exhausted to think why this may not be applicable.
Python:

    x = 2
    if stringy: x = '2'
    print x+x # 4 or 22???
C++:

    int x = 2;
    if(stringy) string x = "2";
    print x+x; // 4 (string x is out of scope)