I am trying to extend std::map
's std::pair
entries with some extra functionality and want to cast such pairs to a child class of pair. Note that this is the "wrong" direction of polymorphism, the child is not the parent. But since the memory layout should be identical as long as I am not introducing additional members in the child class, I am wondering if this is valid.
Here is a minimal example:
#include <iostream>
#include <map>
#include <string>
class Concatenator : public std::pair<const std::string, std::string> {
public:
operator std::string() const { return first + ", " + second; }
};
int main() {
std::map<std::string, std::string> m{{"hello", "world"}};
// Is this defined behaviour?
Concatenator &c{*static_cast<Concatenator *>(&*m.begin())};
std::cout << std::string{c} << std::endl;
}
But since the memory layout should be identical as long as I am not introducing additional members in the child class...
No, that's wrong. That is undefined behavior.
Even without multiple inheritance, there is no guarantee that the memory layout is identical. Even if the memory layout was identical, then it is still undefined behavior. Do not do this.