Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a type in C++

Tags:

c++

types

casting

Is it possible to store a type name as a C++ variable? For example, like this:

type my_type = int; // or string, or Foo, or any other type void* data = ...; my_type* a = (my_type*) data; 

I know that 99.9% of the time there's a better way to do what you want without resorting to casting void pointers, but I'm curious if C++ allows this sort of thing.

like image 551
perimosocordiae Avatar asked Apr 01 '10 17:04

perimosocordiae


People also ask

What data type can store in C?

In C language, basic data types are used to store values in integer and decimal forms. It supports both signed and unsigned literals.

What is a data type in C?

In C programming, data types are declarations for variables. This determines the type and size of data associated with variables. For example, int myVar; Here, myVar is a variable of int (integer) type.

Can you store a type in C++?

In c++0x that specific function is possible, but there's never a place it is useful because the type information is lost when the original variable is. The only thing I can think of to store types polymorphicaly in C++ would be type erasure.

How is data stored in C?

Stack, where automatic variables are stored, along with information that is saved each time a function is called. Each time a function is called, the address of where to return to and certain information about the caller's environment, such as some of the machine registers, are saved on the stack.


1 Answers

No, this is not possible in C++.

The RTTI typeid operator allows you to get some information about types at runtime: you can get the type's name and check whether it is equal to another type, but that's about it.

like image 200
Thomas Avatar answered Sep 19 '22 22:09

Thomas