I'm not sure "data polymorphism" is a actually a thing, but it seemed like a reasonable expression for what I'm looking for: How would you represent multiple types that share a functionality, but operate on different static data?
Take for instance:
class A {
static constexpr std::array<int, 5> m_static_data{1, 2, 3, 4, 5};
public:
int foo(float x) { // do stuff based on m_static_data }
};
class B {
static constexpr std::array<int, 3> m_static_data{42, 43, 44};
public:
int foo(float x) { // do stuff based on m_static_data }
};
Where foo()
is exactly the same between them.
One way would be to define foo
in a base class, and a getter for the data in A and B:
class Base {
virtual std::vector<int> get_data() = 0;
public:
int foo(float x) { // do stuff based on get_data()'s returned value }
};
class A : Base{
std::vector<int> get_data() override { return {1, 2, 3, 4, 5}; }
};
class B : Base{
std::vector<int> get_data() override {return {42, 43, 44}; }
};
But then you would lose all the nice compile time checks and evaluations. Is there a better pattern for doing this sort of thing? And is there a name for it?
Aucun commentaire:
Enregistrer un commentaire