Skip to content

Instantly share code, notes, and snippets.

@skyrpex
Last active October 17, 2015 10:28
Show Gist options
  • Save skyrpex/a5d2c99e82cbbdf8d078 to your computer and use it in GitHub Desktop.
Save skyrpex/a5d2c99e82cbbdf8d078 to your computer and use it in GitHub Desktop.
Experimental ECS C++ implementation using vectors, tuples and optionals
#include <iostream>
#include <tuple>
#include <vector>
#include <experimental/optional>
template<class ...Cs>
class Container
{
public:
template<class T> using Optional = std::experimental::optional<T>;
std::vector<std::tuple<Optional<Cs>...>> elements;
template<class C>
C get(std::size_t index) const
{
return optional<C>(index).value();
}
template<class C>
C get(std::size_t index, C&& defaultValue) const
{
return optional<C>(index).value_or(std::move(defaultValue));
}
template<class C>
void set(std::size_t index, const C& c)
{
optional<C>(index) = c;
}
template<class C, class... Args>
void emplace(std::size_t index, Args&&... args)
{
optional<C>(index).emplace(args...);
}
template<class C>
bool has(std::size_t index) const
{
return optional<C>(index);
}
protected:
template<class C>
const Optional<C>& optional(std::size_t index) const
{
return std::get<Optional<C>>(elements.at(index));
}
template<class C>
Optional<C>& optional(std::size_t index)
{
return std::get<Optional<C>>(elements.at(index));
}
};
int main()
{
Container<int, double> container;
container.elements.resize(10);
container.emplace<int>(0, 69);
std::cout << container.get<int>(0) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment