I want to print variables of many types. I've made a class named IStringable, and some classes that derive from it. In my PrintVariable function I want to check whether the parameter derives from IStringable, and if it does then print it.
class IStringable {
public:
virtual ~IStringable() { }
virtual std::string ToString() const = 0;
}
class Person : public IStringable {
public:
Person(const std::string name) : _name(name) { }
virtual std::string ToString() const { return _name; }
private:
std::string _name;
}
// This does not work as intended, as I don't know how it could be implemented
template <>
void PrintVariable<IStringable>(const IStringable& var) {
std::cout << var.ToString() << std::endl;
}
int main() {
Person p("Foo");
PrintVariable(p);
}
So far I've worked around this problem by just using std::cout << p.ToString() << std::endl; instead, but I'm wondering if there's a better solution to this.