Straight to the code:
class ArithmeticExpressionParser<T> : Parser
{
T num1, num2;
/* ......... */
void ParseNumber()
{
string temp = String.Empty;
while (char.IsDigit(PeekNextToken()))
{
GetNextToken();
temp += Token;
}
num1 = T.Parse(temp); // <<< the problem
}
Basically, if I was using an int or double I would have just use int.Parse etc. I’ve tried casting num1 = (T)temp; , which didn’t work. How can I do this without having to write a custom string to T function?
This assumes that all the types you are converting implement
IConvertible, which will allow you to place a generic constraint on your parser class. If not all types are convertible, you will need to switch conversion methods based on the type (messy).If necessary, you can also implement IConvertible on your own types. There are many methods to implement, but if you are dealing with primitive values it usually doesn’t take too long to implement.
http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx