- 论坛徽章:
- 0
|
- #include <string>
- #include <sstream>
- template <typename T>class type_traits;
- #define TYPE_TRAIT_TYPES(type) \
- template<> class type_traits<type>{ \
- public: \
- static std::string info(){ return #type; } \
- };
- TYPE_TRAIT_TYPES(char)
- TYPE_TRAIT_TYPES(int)
- TYPE_TRAIT_TYPES(float)
- TYPE_TRAIT_TYPES(long)
- TYPE_TRAIT_TYPES(double)
- template <typename T, int i>class type_traits<T[i]>{
- public:
- static std::string info(){
- std::stringstream ss;
- ss<<type_traits<T>::info()<<"["<<i<<"]";
- std::string result;
- ss>>result;
- return result;
- }
- };
- #include <iostream>
- template <typename T>
- std::string get_type(const T &t) {
- return type_traits<T>::info();
- }
- #define print_type(type) \
- std::cout<<"type of \e[32m " \
- << #type << "\e[0m is: " \
- << get_type(type) \
- << std::endl;
- int main(int argc, char *argv[]) {
- print_type("how are you");
- print_type(13);
- print_type(13.65);
- return 0;
- }
复制代码 |
|