Is there an equvalent to Dim/var in C++?
I'm new to C++ and i have a case where vb.nets Dim or C#s var would help me greatly.
i googled around and i found no questions for th开发者_Python百科is? (although search terms with var or dim and C++ seemed to stray easy)
is there an equivalent for this?
Not in the current standard.
However, the new version that is probably due this year (most likely called C++11, but it's also still often referred to as C++0x) has auto
that does that same thing as var
.
It's already supported by recent versions of all big compilers.
For example:
auto MyValue = SomeFunction(); // The compiler will figure out the type of MyValue
You're probably looking for the auto
keyword in C++0x.
As per my comment, Dim does a lot of different things.
If you are looking for a variable that can be anything, or something that will work like
Dim var
var = 1
var = "Hello"
Set var = new Thing
You can use
- void* and cast
- a union type of all the possible thing this variable can be, if these are known in advance
- boost::variant<> - discriminated union, also if all types are known in advance
- boost::any - any type you want, the closest I can think of to Dim
Cliff notes:
boost::any will work for you
In C++ you can use union
s or use a base class and inheritance.
The union
allows you to have an area in memory and organize it in different ways. A base class and inheritance allows you to treat child objects in a common manner.
union
{
int value;
double floating_point;
};
In the union
above, the integer value
and the double precision floating_point
variables occupy the same area (within the union).
The union
may be the closest data structure to a variant record. The Boost library also has a variant data structure, search the web for "boost variant".
精彩评论