代码之家  ›  专栏  ›  技术社区  ›  Maik Klein

在编译时生成类型的唯一ID

  •  5
  • Maik Klein  · 技术社区  · 10 年前

    我想在编译时为每个类型生成一个唯一的id。这在Rust有可能吗?

    到目前为止,我有以下代码

    //Pseudo code
    struct ClassTypeId{
        id: &'static uint
    }
    impl ClassTypeId{
        fn get_type<T>(&mut self) -> &'static uint {
            let _id :&'static uint = self.id + 1;
            self.id = _id;
            _id
        }
    }
    
    let c = ClassTypeId{id:0};
    c.get_type::<i32>();  // returns 1
    c.get_type::<f32>();  // returns 2
    c.get_type::<i32>();  // returns 1
    c.get_type::<uint>(); // returns 3
    

    我从C++库中窃取了这个想法,它看起来像这样

    typedef std::size_t TypeId;
    
            template <typename TBase>
            class ClassTypeId
            {
            public:
    
                template <typename T>
                static TypeId GetTypeId()
                {
                    static const TypeId id = m_nextTypeId++;
                    return id;
                }
    
            private:
    
                static TypeId m_nextTypeId;
            };
    
            template <typename TBase>
            TypeId ClassTypeId<TBase>::m_nextTypeId = 0;
        }
    
    3 回复  |  直到 6 年前
        1
  •  14
  •   Shepmaster Tim Diekmann    9 年前

    std::any::TypeId 这样做:

    use std::any::TypeId;
    
    fn main() {
        let type_id = TypeId::of::<isize>();
        println!("{:?}", type_id);
    }
    

    输出:

    TypeId { t: 4150853580804116396 }
    
        2
  •  8
  •   ArtemGr    10 年前

    这听起来像是位标志的工作!宏:

    #[macro_use] extern crate rustc_bitflags;
    
    bitflags!(
        #[derive(Debug)]
        flags ComponentMask: u8 {
            const Render     = 0b00000001,
            const Position   = 0b00000010,
            const Physics    = 0b00000100
        }
    );
    
    // the set of components owned by an entity:
    let owned_components:  = Render | Position;
    
    // check whether an entity has a certain component:
    if owned_components.contains(Physics) { ... }
    

    http://doc.rust-lang.org/rustc_bitflags/macro.bitflags!.html

        3
  •  0
  •   Shepmaster Tim Diekmann    5 年前

    如果您想手动管理类型ID,可以使用 unique-type-id crate 。它允许您指定类型在特殊文件中具有的ID。它将在编译时生成它们。目前可以通过以下方式使用:

    use unique_type_id::UniqueTypeId;
    #[derive(UniqueTypeId)]
    struct Test1;
    #[derive(UniqueTypeId)]
    struct Test2;
    
    assert_eq!(Test1::id().0, 1u64);
    assert_eq!(Test2::id().0, 2u64);
    

    它既可以使用递增数字生成类型,也可以使用文件中的id。