[英]How to Iterate over number of variadic template Types
I'am currently learning C++ and i am currently building a very simple Entity Component System.我目前正在学习 C++,我目前正在构建一个非常简单的实体组件系统。 For that i have a Function getComponentType which maps each Component to a uint8_t.
为此,我有一个 Function getComponentType,它将每个组件映射到一个 uint8_t。 A Signature is just a std::bitset
签名只是一个 std::bitset
I would like a method like this.我想要这样的方法。
Signature signature = createSignature<TransformComponent, GraphicsComp>();
Lets say TransformComponent gets mapped to 0 and GraphicsComp get mapped to 1. The Signature should now be a std::bitset {1100000...} I know how to do that with non various template methods, the Question is now how would i archive the same with various template types or is there a better solution to do the same.假设 TransformComponent 被映射到 0,GraphicsComp 被映射到 1。签名现在应该是 std::bitset {1100000...} 我知道如何使用非各种模板方法来做到这一点,现在的问题是我将如何存档与各种模板类型相同,或者是否有更好的解决方案来做同样的事情。
template <typename T> Signature createSignature(){
return Signature(((unsigned long long int)1)<<getComponentType<T>());
}
template <typename T, typename R> Signature createSignature(){
return Signature(
((unsigned long long int)1)<<getComponentType<T>() |
((unsigned long long int)1)<<getComponentType<R>()
);
}
template <typename T, typename R, typename S> Signature createSignature(){
return Signature(
((unsigned long long int)1)<<getComponentType<T>() |
((unsigned long long int)1)<<getComponentType<R>() |
((unsigned long long int)1)<<getComponentType<S>()
);
}
template <typename T, typename R, typename S, typename U> Signature createSignature(){
return Signature(
((unsigned long long int)1)<<getComponentType<T>() |
((unsigned long long int)1)<<getComponentType<R>() |
((unsigned long long int)1)<<getComponentType<S>() |
((unsigned long long int)1)<<getComponentType<U>()
);
}
From C++ 17 onward you could use a fold expression:从 C++ 17 开始,您可以使用折叠表达式:
template<typename... T>
return Signature((((unsigned long long int)1) << getComponentType<T>() | ...));
The unsigned long long int cast seems a bit weird, but I left it the same as the question to clarify the use of the fold expression: unsigned long long int 强制转换似乎有点奇怪,但我将其与问题相同以澄清折叠表达式的使用:
(statement | ...)
I believe variadic templates are the way to go here.我相信可变参数模板是 go 的方式。 Something along the lines of
类似的东西
template <typename T, typename ...Args>
Signature createSignature(T t, Args...)
{
return Signature(((unsigned long long int)1)<<getComponentType<T>()) | createSignature(Args...);
}
template<typename T>
Signature createSignature(T t)
{
return Signature(((unsigned long long int)1)<<getComponentType<T>());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.