2
\$\begingroup\$

I am trying to develop an ECS registry. How would you improve this ? First disadvantage comes to my mind is using lambdas might be expensive, however I was not able to replicate functionality using F&& template arguments.

 engine->addEntity(1, 
 Position{1, 1},
 Mesh{"thing.gltf"},
 PhysicsBody{10.0f}
 );
 engine->addEntity(2,
 Position{ 2, 2 },
 Mesh{ "other.gltf" },
 PhysicsBody{ 30.0f }
 );
 engine->entity<Position>(1, [&](auto pos) {
 std::cout << "entity";
 });
 engine->each<Position, Mesh>([] (int id, Position& pos, Mesh& mesh) {
 std::cout << "entity" << id;
 });
 template<typename First>
 void entity(int id, std::function<void(First&)> callback)
 {
 auto comp = storage<First>()->get(id);
 if (!comp) return;
 callback(*comp);
 }
 template<typename First, typename...Rest>
 void entity(int id, std::function<void(Rest&...)> callback)
 {
 auto comp = storage<First>()->get(id);
 if (!comp) return;
 entity<Rest...>(id, [](Rest&...args) {
 callback(*comp, args...)
 });
 }
 template<typename T, typename...Rest, typename F>
 void each(F&& callback)
 {
 storage<T>()->forEach([&](int id, T& value) {
 entity<Rest...>(id, [&](Rest&...args) {
 callback(id, value, args...);
 });
 });
 }
Reinderien
70.9k5 gold badges76 silver badges256 bronze badges
asked Apr 25, 2020 at 12:25
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

using lambdas might be expensive

Why do you think that?

Lambdas are simply syntactic hand waving for class functors (that have been around for over 3 decades). Functors are considered (in general) to be much more efficient than standard functions (especially when used by templates) as the compiler can do a lot of optimizations on them.

auto x = [&capture](X const& parm){ /* BODY */ }

You can consider as syntactic sugar for:

class CompilerNamedType
{
 TypeOfCapure& capture;
 public:
 CompilerNamedType(TypeOfCapure& capture)
 : capture(capture)
 {}
 CompilerCalculatedReturnType operator()(X const& param) const
 {
 /* BODY */
 }
};
CompilerNamedType x(capture);

answered Apr 25, 2020 at 19:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.