Programing

C ++에서 'typeid'와 'typeof'

lottogame 2020. 6. 17. 20:25
반응형

C ++에서 'typeid'와 'typeof'


C ++ typeidtypeofC ++ 의 차이점이 무엇인지 궁금합니다 . 내가 아는 것은 다음과 같습니다.

  • typeidC ++ 헤더 파일 typeinfo에 정의 된 type_info 문서에 언급되어 있습니다.

  • typeofC 및 C ++ Boost 라이브러리 의 GCC 확장에 정의되어 있습니다.

또한, 내가 찾은 곳에서 내가 만든 typeid예상 코드를 반환하지 않는 테스트 코드 테스트가 있습니다. 왜?

main.cpp

#include <iostream>  
#include <typeinfo>  //for 'typeid' to work  

class Person {  
    public:
    // ... Person members ...  
    virtual ~Person() {}  
};  

class Employee : public Person {  
    // ... Employee members ...  
};  

int main () {  
    Person person;  
    Employee employee;  
    Person *ptr = &employee;  
    int t = 3;  

    std::cout << typeid(t).name() << std::endl;  
    std::cout << typeid(person).name() << std::endl;   // Person (statically known at compile-time)  
    std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)  
    std::cout << typeid(ptr).name() << std::endl;      // Person * (statically known at compile-time)  
    std::cout << typeid(*ptr).name() << std::endl;     // Employee (looked up dynamically at run-time  
                                                       // because it is the dereference of a pointer
                                                       // to a polymorphic class)  
 }  

산출:

bash-3.2$ g++ -Wall main.cpp -o main  
bash-3.2$ ./main   
i  
6Person  
8Employee  
P6Person  
8Employee

C ++ 언어는와 같은 것이 없습니다 typeof. 컴파일러 별 확장을보고 있어야합니다. GCC에 대해 이야기하고 있다면 typeof키워드를 통해 비슷한 기능이 C ++ 11에 decltype있습니다. 다시, C ++에는 그러한 typeof키워드 가 없습니다 .

typeid런타임에 유형 식별 정보를 리턴하는 C ++ 언어 연산자입니다. 기본적으로 type_info다른 type_info객체 와 동등한 객체를 반환 합니다.

반환 된 type_info객체 의 정의 된 유일한 속성은 동일성과 비등가 비교 가능하다는 것입니다. 즉, type_info서로 다른 유형을 type_info설명 하는 객체는 동일 하지 않은 것을 비교해야하지만 동일한 유형을 설명 하는 객체는 동일하게 비교해야합니다. 그 밖의 모든 것은 구현 정의되어 있습니다. 다양한 "이름"을 리턴하는 메소드는 사람이 읽을 수있는 것은 리턴하지 않으며, 아무것도 리턴하지는 않습니다.

또한 위의 내용은 표준에 명시 적으로 언급하지 않았지만 typeid동일한 유형 의 연속 응용 프로그램이 다른 type_info객체를 반환 할 수 있음을 의미 합니다 (물론 여전히 동일하게 비교해야 함).


이 둘의 주요 차이점은 다음과 같습니다.

  • typeof는 컴파일 타임 구문이며 컴파일 타임에 정의 된대로 형식을 반환합니다.
  • typeid는 런타임 구성이므로 값의 런타임 유형에 대한 정보를 제공합니다.

typeof 참조 : http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid 참조 : https://en.wikipedia.org/wiki/Typeid


typeid can operate at runtime, and return an object describing the run time type of the object, which must be a pointer to an object of a class with virtual methods in order for RTTI (run-time type information) to be stored in the class. It can also give the compile time type of an expression or a type name, if not given a pointer to a class with run-time type information.

typeof is a GNU extension, and gives you the type of any expression at compile time. This can be useful, for instance, in declaring temporary variables in macros that may be used on multiple types. In C++, you would usually use templates instead.


Answering the additional question:

my following test code for typeid does not output the correct type name. what's wrong?

There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.


These are two different tools. typeof returns the type of an expression, but it is not standard. In C++0x there is something called decltype which does the same job AFAIK.

decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];

Whereas typeid is used with polymorphic types. For example, lets say that cat derives animal:

animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
    // the object is of type cat! but the pointer is base pointer.
}

typeid provides the type of the data at runtime, when asked for. Typedef is a compile time construct that defines a new type as stated after that. There is no typeof in C++ Output appears as (shown as inscribed comments):

std::cout << typeid(t).name() << std::endl;  // i
std::cout << typeid(person).name() << std::endl;   // 6Person
std::cout << typeid(employee).name() << std::endl; // 8Employee
std::cout << typeid(ptr).name() << std::endl;      // P6Person
std::cout << typeid(*ptr).name() << std::endl;     //8Employee

You can use Boost demangle to accomplish a nice looking name:

#include <boost/units/detail/utility.hpp>

and something like

To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

참고URL : https://stackoverflow.com/questions/1986418/typeid-versus-typeof-in-c

반응형