如何解决如何使用模板化别名或 const 变量来缩写静态 const 变量?
我正在用 C++17 编写一个实体组件系统作为练习。作为示例,我希望将每个组件类型(表示为一个结构体)与一个唯一标识符相关联,该标识符可用作组件注册表中位集向量的索引。这使用模板化结构 ComponentType
工作。但是,每次我想获取值时都写 ComponentType<Tag>::type
感觉很冗长。我更喜欢使用 component_type_t<Tag>
之类的东西。但是,使用模板化别名和以下实现进行编译失败,尽管它可以编译,但使用会产生以下输出。有没有更好的方法来解决这个问题?
0
1
2
0
0
0
代码:
#include <iostream>
namespace ECS {
struct ComponentTraits {
using component_type = unsigned int;
protected:
static component_type types;
};
using component_type = ComponentTraits::component_type;
component_type ComponentTraits::types = 0;
template<typename Component>
struct ComponentType : public ComponentTraits {
static const component_type type;
};
template<typename Component>
const component_type ComponentType<Component>::type = types++;
template<typename Component>
const component_type component_type_t = ComponentType<Component>::type;
//Components
struct Tag {};
struct Transform {};
struct Mesh {};
// and so on...
////Won't compile
//template<typename Component>
//using component_type_t = ComponentType<Component>::type;
};
int main() {
using namespace ECS;
std::cout << ComponentType<Tag>::type << std::endl;
std::cout << ComponentType<Transform>::type << std::endl;
std::cout << ComponentType<Mesh>::type << std::endl;
std::cout << component_type_t<Tag> << std::endl;
std::cout << component_type_t<Transform> << std::endl;
std::cout << component_type_t<Mesh> << std::endl;
return 0;
}
解决方法
您的模板化 using
未编译的原因是您的 ComponentType
不包含别名,它包含变量存储。
using component_type = unsigned int;
static const component_type type; // this is not an alias
template<typename Component>
using component_type_t = ComponentType<Component>::type;
要修复该错误,您需要使用 decltype
获取其类型:
template<typename Component>
using component_type_t = decltype(ComponentType<Component>::type);
但这引发了另一个问题,component_type_t
从来没有真正保存过你期望的值,它实际上保存了 component_type
,它是 unsigned int
没有分配任何值(因为它是一个别名) ,所以当你打电话时:
std::cout << component_type_t<Tag> << std::endl;
std::cout << component_type_t<Transform> << std::endl;
std::cout << component_type_t<Mesh> << std::endl;
它打印 0,因为您的编译器将 0 分配给未初始化的变量,您不应该依赖于此,因为不同的编译器可能会以不同的方式处理此问题。
因此要解决此问题,您需要将值传递给变量而不是传递其类型:
template<typename T>
component_type component_type_t<T> = ComponentType<T>::type;
你的输出将是:
0 // Tag
1 // Transform
2 // Mesh
0 // Tag
1 // Transform
2 // Mesh
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。