Replace typeerasure submodule

This commit is contained in:
Mathieu Maret 2022-09-24 23:24:40 +02:00
parent 27c6c94cfa
commit 91ff914e2d
2 changed files with 49 additions and 1 deletions

@ -1 +0,0 @@
Subproject commit 5c7eb2826ce6b63a6372c0a0b8602a30bc7f82c8

View File

@ -0,0 +1,49 @@
#include <memory>
#include <string>
#include <vector>
#include <iostream>
class Measure {
struct MeasureConcept {
protected:
virtual void *getPtr() = 0;
public:
virtual ~MeasureConcept() = default;
template <typename T>
T get() { return *reinterpret_cast<T*>(getPtr()); }
};
template <typename T>
class MeasureAdapter : public MeasureConcept {
T v;
public:
MeasureAdapter(const T& v) : v(v) {}
T get() const { return v; }
protected:
void *getPtr() override { return &v; }
};
std::shared_ptr<MeasureConcept> d;
public:
template <typename T>
Measure(const T& v) : d(new MeasureAdapter<T>(v)) {}
template <typename T>
T get() { return d->get<T>(); }
};
int main() {
using namespace std::string_literals;
std::vector<Measure> measures;
measures.push_back(12);
measures.push_back(42.5f);
measures.push_back("toto"s);
measures.push_back(std::vector<int>{ 1, 2, 3 });
std::cout << measures[0].get<int>() << std::endl;
std::cout << measures[1].get<float>() << std::endl;
std::cout << measures[2].get<std::string>() << std::endl;
for (auto &v : measures[3].get<std::vector<int>>())
std::cout << '[' << v << ']' << std::endl;
return 0;
}