Answer the question
In order to leave comments, you need to log in
Using variadic function template with no arguments?
I have a class object Entity
that contains a list of components. std::list<Component*> m_components
The components themselves are classes that inherit from the base class. Component
With the help of a function, bool HasComponent<T>
I can check for the presence of a specific component:
template<typename T> bool HasComponent<T> {
T instance; //создаю экземпляр компонента
for (auto component : m_components) //for each
if (component->GetType() == instance.GetType()) { //если типы компонентов совпадают
return true; //возвращаем true
}
//...
Entity mario;
if (mario.HasComponent<Velocity>) print("Mario can move!"); //пример использования
bool HasComponents<Health, Velocity, Sprite>();
void foo(Args... args)
. Answer the question
In order to leave comments, you need to log in
Look... in the proposed code, I already see a bit of a mess, so I suggest a slightly messy option. :)
This problem can be solved by several methods of metaprogramming at once. The proposed solution is one of them.
template< typename TComponentType >
bool HasComponent()
{
return ...;
};
template< typename... TComponentTypes >
bool HasComponents()
{
// Это тип предиката для проверки наличия одного компонента.
using CheckingPred = bool (*)();
// Это тип листа проверки.
using PredList = std::array<CheckingPred, sizeof...( TComponentTypes )>;
// Определяем лист проверки, следи за руками... :-)
PredList predicates{{ HasComponent<TComponentTypes>... }};
// Проверяем!
return std::all_of( predicates.begin(), predicates.end(), []( CheckingPred stored_pred ) -> bool { return stored_pred(); } );
};
For example in C++17:
1) Rename your current HasComponent to HasComponent_impl and make it private.
2) Create a new HasComponent:
template<typename... Ts> bool HasComponent()
{
return (HasComponent_impl<Ts>() && ...);
}
Example. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question