Jak potem rozwiązać problem podstawowych operacji np. łączenia stringów, czy zwykłego arytmetycznego dodawania?
W pseudokodzie coś w stylu:
operator + (Value A, Value B): Value
{
Value result;
if ((A.type == vtInt) && (B.type == vtInt))
{
result.type = vtInt;
result._int = A._int + B._int;
} else
if ((A.type == vtInt) && (B.type == vtFloat))
{
result.type = vtFloat;
result._float = A._int + B._float;
} else
if ((A.type == vtFloat) && (B.type == vtInt))
{
result.type = vtFloat;
result._float = A._float + B._int;
} else
if ((A.type == vtFloat) && (B.type == vtFloat))
{
result.type = vtFloat;
result._float = A._float + B._float;
}
if ((A.type = vtString) && (B.type == vtString))
{
result.type = vtString;
result._string = A._string + B._string;
} else
// if (isOperatorOverloaded(A.type, B.type)) (jeżeli w swoim języku umożliwiasz overloadowanie operatorów, musisz dodatkowo to wziąć pod uwagę)
throw new InvalidOperatorException(A.typeToString, B.typeToString);
return result;
}
Sprawę możesz sobie nieco ułatwić makrami.
W przypadku korzystania z klas wyglądałoby to nieco inaczej:
```
class Value
{
abstract virtual Value Add(Value B);
abstract virtual Value Sub(Value B);
// i tak dalej
}
```
Przykładowo `IntValue` mogłoby wyglądać tak:
```
class IntValue: Value
{
Value Add(Value B)
{
Value result;
if ((this.type == vtInt) && (B.type == vtInt)) // int + int
{
result.type = vtInt;
result._int = ...
} else
i tak dalej
return result;
}
}