3

I am trying use a variadic template in an && statement, but i dont know how to actually do it. Can somebody explain to me how i can programm a function like this one:

using EntitySet = std::vector<Entity>;
template<typename... TArgs>
EntitySet getEntitesWith()
{
    EntitySet entitySet;
    for(const Entity& entity : m_entitySet)
    {
        if (entity.hasComponent<T1>() && entity.hasComponent<T2>() && ...)
        {
            entitySet.push_back(entity);
        }
    }
    return entitySet;
}

entity.hasComponent<>() returns true if the entity has a Component of the type that is passed into the function

Edit:

i just tried the Fold Expression in c++17 and when i tried to do it like @Igor Tandetnik and @oisyn told me to i got an Unexpected ... Token Error. But when i wrote the code like this:

if (( ... && entity.hasComponent<TArgs>()))

With an extra () i got an internal compiler error and have no idea on what im doing wrong. anybody have an idea on why this is happening?

Community
  • 1
  • 1
Dolfos
  • 98
  • 1
  • 9
  • 2
    C++17: http://en.cppreference.com/w/cpp/language/fold – chris Jan 23 '18 at 13:01
  • With a C++17-conforming compiler, you could write `if (entity.hasComponent() && ...)` – Igor Tandetnik Jan 23 '18 at 13:01
  • I am not using c++17, is there an easy way to do it in c++14? – Dolfos Jan 23 '18 at 13:07
  • 2
    Pre-C++17, something like this: `auto list = {entity.hasComponent(), ...}; if (std::all_of(std::begin(list), std::end(list), [](bool v) { return v; }))` This is not quite equivalent in that it doesn't short-circuit - doesn't stop checking on the first `false` result. For that, you need a recursive helper template. – Igor Tandetnik Jan 23 '18 at 13:07
  • @IgorTandetnik Beware that that is a right fold. If you want it to parse as in the example, you'd have to write `if (... && entity.hasComponent())` – oisyn Jan 23 '18 at 22:34

0 Answers0