What is the correct way to implement the following?
Without meaning to sound difficult, it really depends on exactly what you want to achieve.
I'm going to make a guess that we're simply be asking an object what type it is, regardless of which interface we're calling on:
struct Base {
virtual ~Base() = default;
virtual const std::string id() const {
return "Base";
}
};
struct Derived : Base {
virtual const std::string id() const override {
return "Derived";
}
};
Here's another way:
struct Base {
virtual Base(std::string ident = "Base")
: _id(std::move(ident))
{}
virtual ~Base() = default;
std::string& id() const {
return _id;
}
private:
std::string _id;
};
struct Derived : Base {
Derived() : Base("Derived") {}
};
And another, using value is interface, but note that this will disable the assignment operator
struct Base {
virtual Base(std::string ident = "Base")
: id(std::move(ident))
{}
virtual ~Base() = default;
const std::string id;
};
struct Derived : Base {
Derived() : Base("Derived") {}
};
This list is by no means exhaustive.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…