C++ — Як вивести тип будь-якого об’єкта

Крок 1: Використовуємо decltype(obj) для отримання типу будь-якого об'єкта.

Крок 2: Визначаємо шаблон функції з одним параметром шаблону типу. У тілі шаблону функції використовуємо змінну компілятора PRETTY_FUNCTION для отримання імені інстанціованої функції шаблону, з якого ми можемо витягнути аргумент типу шаблону:

template <typename T>   
void display_type() {  
 std::string func_name(__PRETTY_FUNCTION__);  
 std::string tmp = func_name.substr(func_name.find_first_of("[") + 1);  
 std::string type = "type" + tmp.substr(1, tmp.size() - 2);  
 std::cout << type << std::endl;  
}

Крок 3: Передаємо decltype(obj) у шаблон функції:

display_type();

Конкретний приклад:

#include <iostream>  
#include <string>  

template <typename T>   
void display_type() {  
 std::string func_name(__PRETTY_FUNCTION__);  
 std::string tmp = func_name.substr(func_name.find_first_of("[") + 1);  
 std::string type = "type" + tmp.substr(1, tmp.size() - 2);  
 std::cout << type << std::endl;  
}  

void dummy_func(const char* str) {  
 std::cout << str << std::endl;  
}  

int main(int argc, char** argv) {  
 std::string test_str("test");  
 display_type<decltype(test_str)>();  
 display_type<decltype(dummy_func)>();  
}

Виведення:

$ ./main   
type = std::__cxx11::basic_string  
type = void (const char *)




Перекладено з: [C++ — How to print type of any object](https://medium.com/@ngocson2vn/c-how-to-print-type-of-any-object-48c64195a21c)

Leave a Reply

Your email address will not be published. Required fields are marked *