Skip to content

Instantly share code, notes, and snippets.

@sergeant-wizard
Last active December 3, 2017 21:05
Show Gist options
  • Save sergeant-wizard/f8a3863af7d8cb4a753ef33e3e1ff169 to your computer and use it in GitHub Desktop.
Save sergeant-wizard/f8a3863af7d8cb4a753ef33e3e1ff169 to your computer and use it in GitHub Desktop.
vector with generic types of elements
#include <vector>
#include <iostream>
// library code
template<class T>
double internal_pose(const T& data) {
std::cout << "not implemented error" << std::endl;
}
class Element {
public:
Element() {}
Element(const Element& other) {
_impl = other._impl->clone();
}
template<class T>
Element(const T& other):
_impl(new ElementWrapper<T>(other))
{ }
virtual ~Element() {
delete _impl;
}
double pose() const {
return _impl->pose();
}
private:
struct ElementImpl {
virtual ElementImpl* clone() = 0;
virtual double pose() const = 0;
};
template<class T>
struct ElementWrapper: ElementImpl {
ElementImpl* clone() {
return new ElementWrapper(_data);
}
ElementWrapper(const T& data): _data(data) {
}
double pose() const {
internal_pose(_data);
}
T _data;
};
ElementImpl* _impl;
};
// user code
class SomeUserClass { };
void internal_pose(const SomeUserClass& data) {
std::cout << "user implementation" << std::endl;
}
int main(void) {
std::vector<Element> elements;
elements.push_back(SomeUserClass());
for (std::size_t i = 0; i < elements.size(); ++i) {
elements[i].pose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment