C++ Shorten subsequent function calls

。_饼干妹妹 提交于 2019-12-05 23:15:21
  1 #include <iostream>
  2 #include <string>
  3
  4 using namespace std;
  5
  6 class A {
  7   public:
  8    std::string x;
  9    A () {
 10      x += "a";
 11    }
 12
 13    std::string ax() {  //imagine this to be some object.
 14     return x;
 15    }
 16 };
 17
 18 int main () {
 19   A a;
 20   auto y = [] (decltype(a)& a) {
 21     return [&a] () {
 22       return a.ax(); //imagine this to be a big chain like yours. I just wanted to give you a working example, so I'm not doing your calls.
 23     };
 24   };
 25   std::cout << y(a)().at(0) << std::endl; //TADA!! this works
 26   return 1;
 27 }

This can be simplified, and I will leave it upto you. I'm just illustrating how to alias, (without even knowing the types).

you can do something similar with function pointers and then alias as many steps as you like and return at whichever stage you want.

The idea is of having a lambda inside another lambda, this way you do not have to worry that the object changed since it is going to do forwarding not store the object. This way all functions in the chain are called at each invocation of the lamba as it returns the inner lambda that you invoke.

If you think carefully, you can store the function, you don't need to do y(a), it was written in a rush.

auto const p = GetCurrentContext()->GetEntityManager();
p->CreateEntity();

Under reasonable assumptions of what the code is about.

There is also an assumption, implicit in your question, that the result from GetEntityManager will be the same in each call in the original code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!