Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Thinking In C++, 2nd Edition, Volume 2 Standard Libraries& Advanced Topics - Eckel B..pdf
Скачиваний:
313
Добавлен:
24.05.2014
Размер:
2.09 Mб
Скачать

void pointers

Run-time type identification doesn’t work with void pointers:

//: C08:Voidrtti.cpp

// RTTI & void pointers #include <iostream> #include <typeinfo> using namespace std;

class Stimpy { public:

virtual void happy() {} virtual void joy() {} virtual ~Stimpy() {}

};

int main() {

void* v = new Stimpy; // Error:

//! Stimpy* s = dynamic_cast<Stimpy*>(v); // Error:

//! cout << typeid(*v).name() << endl; } ///:~

A void* truly means “no type information at all.”

Using RTTI with templates

Templates generate many different class names, and sometimes you’d like to print out information about what class you’re in. RTTI provides a convenient way to do this. The following example revisits the code in Chapter XX to print out the order of constructor and destructor calls without using a preprocessor macro:

//: C08:ConstructorOrder.cpp // Order of constructor calls #include <iostream>

#include <typeinfo> using namespace std;

template<int id> class Announce { public:

Announce() {

cout << typeid(*this).name()

Chapter 17: Run-Time Type Identification

408

Соседние файлы в предмете Программирование