我想在编译时为每种类型生成一个唯一的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
Run Code Online (Sandbox Code Playgroud)
我从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;
}
Run Code Online (Sandbox Code Playgroud)
std::any::TypeId 做那样的事情:
use std::any::TypeId;
fn main() {
let type_id = TypeId::of::<isize>();
println!("{:?}", type_id);
}
Run Code Online (Sandbox Code Playgroud)
输出:
TypeId { t: 4150853580804116396 }
Run Code Online (Sandbox Code Playgroud)
这听起来像是bitflags的工作!宏:
#[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) { ... }
Run Code Online (Sandbox Code Playgroud)
http://doc.rust-lang.org/rustc_bitflags/macro.bitflags!.html