mirror of
https://github.com/allankoechke/cparse.git
synced 2026-11-30 17:11:31 +00:00
This change allow to the user of the `TokenMap_t` to: - Implicit instantiate a BaseToken* from a double. - Explicit (and safely) convert a BaseToken* to a double. - Make use of `cout << map["var"]` - Make use of a serialization function `str()` The packToken class is not intended to be used on the internals of the calculate and compile functions, because it would add some unnecessary function calls everytime a Token is accessed, but it is useful to simplify the Token access for the API user.
67 lines
1.4 KiB
C++
67 lines
1.4 KiB
C++
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <iostream>
|
|
#include "shunting-yard.h"
|
|
#include "shunting-yard-exceptions.h"
|
|
|
|
packToken& packToken::operator=(int t) {
|
|
if(base) delete base;
|
|
base = new Token<double>(t, NUM);
|
|
return *this;
|
|
}
|
|
|
|
packToken& packToken::operator=(double t) {
|
|
if(base) delete base;
|
|
base = new Token<double>(t, NUM);
|
|
return *this;
|
|
}
|
|
|
|
// Used mainly for testing
|
|
bool packToken::operator==(const packToken& token) const {
|
|
if(!base) {
|
|
return token.base == 0;
|
|
} else if(!token.base) {
|
|
return base == 0;
|
|
} else if(token.base->type != base->type) {
|
|
return false;
|
|
} else {
|
|
// Compare strings to simplify code
|
|
return token.str().compare(str()) == 0;
|
|
}
|
|
}
|
|
|
|
TokenBase* packToken::operator->() const {
|
|
return base;
|
|
}
|
|
|
|
std::ostream& operator<<(std::ostream &os, const packToken& t) {
|
|
return os << t.str();
|
|
}
|
|
|
|
double packToken::asDouble() const {
|
|
if(base->type != NUM || !base) {
|
|
throw bad_cast(
|
|
"The Token is not a number!");
|
|
}
|
|
return static_cast<Token<double>*>(base)->val;
|
|
}
|
|
|
|
std::string packToken::str() const {
|
|
std::stringstream ss;
|
|
if(!base) return "undefined";
|
|
switch(base->type) {
|
|
case NONE:
|
|
return "None";
|
|
case OP:
|
|
return static_cast<Token<std::string>*>(base)->val;
|
|
case VAR:
|
|
return static_cast<Token<std::string>*>(base)->val;
|
|
case NUM:
|
|
ss << asDouble();
|
|
return ss.str();
|
|
default:
|
|
return "unknown_type";
|
|
}
|
|
}
|