Created
December 13, 2012 22:38
-
-
Save kbenzie/4280733 to your computer and use it in GitHub Desktop.
C++ where T : Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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>(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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