Generic List Items
unknown
c_cpp
4 years ago
1.2 kB
15
Indexable
#include <list>
#include <string>
#include <memory>
#include <cstdio>
class IParameter {
public:
virtual ~IParameter() = default;
};
template<typename T>
class Parameter : public IParameter{
private:
T value;
public:
T GetValue() {
return value;
}
explicit Parameter(T value) : value(value) {}
~Parameter() override = default;
};
class Context {
private:
std::list<std::unique_ptr<IParameter>> list;
public:
template<typename P>
void Add(P p) {
list.push_back(std::make_unique<Parameter<P>>(Parameter<P>(p)));
}
template<typename P>
P Get(int index) const {
unsigned N = index;/* index of the element you want to retrieve */
if (list.size() > N) {
auto iterator = std::next(list.begin(), N);// 'it' points to the element at index 'N'
auto ptr = iterator->get();
auto value = (Parameter<P>*) (ptr);
return value->GetValue();
}
}
};
int main() {
Context context;
context.Add<std::string>("Text string");
context.Add<int32_t>(32);
printf("Item: %i \n", context.Get<int32_t>(1));
printf("Item: %s \n", context.Get<std::string>(0).c_str());
}
Editor is loading...