Reputation: 159
What is the C++ equivalent of C# object type?
I want to do the C++ equivalent of this:
public enum TokenType {
Number,
Operator,
}
public class Token
{
TokenType type;
object value;
public Token(TokenType type, object value)
{
switch (type)
{
case TokenType.Number:
break;
case TokenType.Operator:
break;
default:
// throw some error
break;
}
this.type = type;
this.value = value;
}
}
I cannot use a template argument for the class because I do not know if the input is going to be a char
, double
or string
, and I need to declare a Token
before knowing.
Upvotes: 0
Views: 1053
Reputation: 1797
You would need a lot of casting in there but a void* in C++ represents a pointer to Anything. Think of it as a general data store, no length attached to it or anything, just a position.
Depending on what else you need to do it might come in handy.
You can use some try{}
wrapped casts to see if it is one of your accepted types
Upvotes: 1
Reputation: 180935
Unlike C#, C++ does not have a total type hierarchy. There is no base type int
and std::string
share. In fact int
doesn't even have a base type, it is a fundamental type (built in) and is not a class type.
This means you have to great lengths to achieve something like the C# code. If you know that the types will be limited to some set of types then you can use a std::variant
. If you don't have any such limitations then you have to use a std::any
. std::variant
is like/is a tagged union where std::any
utilizes type erasure to store any object inside it. You can then use the visitor pattern to modify the object stored in the variant
/any
. Since std::variant
has a known set of types it gives you more ways to access they type stored in it.
Upvotes: 2