0

我正在编写一个实体组件系统作为 C++17 的练习。我想让每个组件类型(表示为一个结构)与一个唯一标识符相关联,该标识符可用作组件注册表中位集向量的索引,例如。这可以使用模板化的 struct ComponentTypeComponentType<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;
}
4

1 回答 1

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_typeunsigned 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
于 2021-02-02T06:17:59.307 回答