I want to generate a unique id for every type at compile time. Is this possible in Rust?
So far, I have the following code
//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
I stole this idea from a C++ library, which looks like this
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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…