I have created a Node class that I am using for various projects in my data structures class(at school) and I am overloading the insertion operator <<
. I am using std::any
for my container datatype inside Node class and am using std::any_cast
to insert this data into a stream whenever possible. Std::any_cast
requires that I know the datatype beforehand, and so I've come up with a hacky way to get this information by detangling the value typename into a string and then using a ton of else if statements to compare this string, as you can see in my code below... I'm looking for a different solution or even some advice about why this approach is fundamentally wrong and how to go about making better programming decisions. Lay it on me, I need help and can take it!
friend std::ostream& operator << (std::ostream& out, Node& n){
std::string t;
t = abi::__cxa_demangle(n.value.type().name(), 0, 0, 0);;
if (t.find("string") != std::string::npos) { out << std::any_cast<std::string>(n.value); }
else if (t == "unsigned long long int") { out << std::any_cast<unsigned long long int>(n.value); }
else if (t == "unsigned long int") { out << std::any_cast<unsigned long int>(n.value); }
else if (t == "long long int") { out << std::any_cast<long long int>(n.value); }
else if (t == "long int") { out << std::any_cast<long int>(n.value); }
else if (t == "unsigned short int") { out << std::any_cast<unsigned short int>(n.value); }
else if (t == "short int"){ out << std::any_cast<short int>(n.value); }
else if (t == "int") { out << std::any_cast<int>(n.value); }
else if (t == "long double") { out << std::any_cast<long double>(n.value); }
else if (t == "double") { out << std::any_cast<double>(n.value); }
else if (t == "float") { out << std::any_cast<float>(n.value); }
else if (t == "bool") { out << std::any_cast<bool>(n.value); }
else if (t == "unsigned char") { out << std::any_cast<unsigned char>(n.value); }
else if (t == "signed char") { out << std::any_cast<signed char>(n.value); }
else if (t == "char") { out << std::any_cast<char>(n.value); }
else { out << t; };
return out;
};
type()
returns atype_info const &
, you can compare that totypeid(std::string)
to find out if it's a string. \$\endgroup\$