Skip to content

Instantly share code, notes, and snippets.

@kbenzie
Created December 13, 2012 22:38
Show Gist options
  • Save kbenzie/4280733 to your computer and use it in GitHub Desktop.
Save kbenzie/4280733 to your computer and use it in GitHub Desktop.
C++ where T : Type
#include "where_T.h"
#include <iostream>
struct IComponent {
virtual void init = 0;
virtual void update(double dt) = 0;
virtual void render() = 0;
}
struct ConcreateComponent : public IComponent {
void init() {}
void update(double dt) {}
void render() {}
}
struct NotComponent {
void init() {}
void update(double dt) {}
void render() {}
}
struct IComponentCollection {
where_T(IComponent, void) add(T component, bool overwrite);
where_T(IComponent, T) find();
where_T(IComponent, T) contains();
where_T(IComponent, void) remove();
};
struct ComponentCollection : IComponentCollection {
where_T(IComponent, void) add(T component, bool overwrite) {
std::cout << "add template working" << std::endl;
}
where_T(IComponent, T) find();
where_T(IComponent, T) contains() {
std::cout << "contains template working" << std::endl;
return true;
}
template <class T>
typename std::enable_if<std::is_base_of<Type, void>::value, Return>::type remove() {
std::cout << "remove template working" << std::endl;
return true;
}
};
where_T(IComponent, T) ComponentCollection::find() {
std::cout << "find template working" << std::endl;
return T();
}
int main() {
auto collection = ComponentCollection();
auto comp = ConcreateComponent();
auto notComp = NotComponent();
collection.add(comp, false);
collection.contains<Comp>();
collection.find<Comp>();
collection.remove<Comp>();
collection.contains<NotComp>();
}
#include <type_traits>
#define where_T(Type, Return) \
template <class T> \
typename std::enable_if<std::is_base_of<Type, T>::value, Return>::type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment