1 2 3 4 5 6 7 8 9 | fn main(){ let x = 123; println!("{}", type_of(x)); } fn type_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } |
c++だと、typeid
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> #include <typeinfo> struct Base {}; struct Derived : public Base {}; struct PolyBase {virtual void member(){}}; struct PolyDerived : public PolyBase {}; int main() { int i; int* pi; std::cout << "int is: " << typeid(int).name() << std::endl; std::cout << "i is: " << typeid(i).name() << std::endl; std::cout << "pi is: " << typeid(pi).name() << std::endl; std::cout << "*pi is: " << typeid(*pi).name() << std::endl; std::cout << std::endl; Derived derived; Base *pbase = &derived; std::cout << "derived is: " << typeid(derived).name() << std::endl; std::cout << "*pbase is: " << typeid(*pbase).name() << std::endl; std::cout << std::boolalpha << "same type? " << (typeid(derived) == typeid(*pbase)) << std::endl; std::cout << std::endl; PolyDerived polyderived; PolyBase* ppolybase = &polyderived; std::cout << "polyderived is: " << typeid(polyderived).name() << std::endl; std::cout << "*ppolybase is: " << typeid(*ppolybase).name() << std::endl; std::cout << std::boolalpha << "same type? " << (typeid(polyderived) == typeid(*ppolybase)) << std::endl; } |
1 2 3 4 5 6 7 8 9 10 | fn main(){ let i = 10; let j = 3.14; println!("{}", type_of(i)); println!("{}", type_of(j)); } fn type_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } |
derivedは派生。rustはclassがなくstructとimplなので、baseとderivedという概念があるか不明。。