Skip to content

Instantly share code, notes, and snippets.

@erikzenker
Created October 3, 2018 18:30
Show Gist options
  • Save erikzenker/fe44d9a6283ba9d018dd3206c471b45f to your computer and use it in GitHub Desktop.
Save erikzenker/fe44d9a6283ba9d018dd3206c471b45f to your computer and use it in GitHub Desktop.
C++ MetaClass CookBook
// API Documentation was created based on the presentation of Herb Sutter on CppCon 2018:
// https://www.youtube.com/watch?v=80BZxujhY38
// and the original propsal:
// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0707r3.pdf
// and test from the implementation repo
// https://github.com/asutton/clang/tree/095a810d0514ccc9b3ea66c546a2adc7384449ca/test/CXX/meta
// Create a meta class
template <typename T>
constexpr void meta_class(T source){
// Do something with the source class
}
// Apply the meta class to a class
class(meta_class) MyClass {
};
//
// Reflections
//
// Member function of class source
source.functions();
source.member_functions();
// Get the return type of the member function
function.return_type();
// Member variables of class source
source.variables();
source.member_variables();
// Get the type of a member variable
variable.type();
// Name of member function
function.name();
// Compare member function name to a string
if(std::strcmp(function.name(), "foo")==0){
// Do something on the function
}
// Iterate over a list of meta information
for... (auto variable: source.variables){
// Do something on variable
}
// Check for public or private
variable.is_public();
variable.is_private();
function.is_public();
function.is_private();
// Check for constructor / destructor
function.is_constructor();
function.is_destructor();
//
// Generation
//
// Generate a public member function
__generate __fragment struct {
int bar(int a){return a;}
};
// Generate a private member function
__generate __fragment class {
int bar(int a){return a;}
};
// Generae a public member variable
__generate __fragment struct {
int b;
}
// Generae a private member variable
__generate __fragment class {
int b;
}
// Make member variable private
variable.make_private();
// Make member variable public
variable.make_public();
// Make member function private
function.make_private();
// Make member function public
function.make_public();
// Make member function pure virtual
function.make_pure_virtual();
// Generate member function with custom name and type
__generate __fragment struct {
typename(variable) idexpr("get_", variable)() const {
return idexpr(variable);
}
};
//
// Compiler object
//
// Print generate code of Test class
constexpr {compiler.debug($Test);}
// Assert on generated code
compiler.require(!source.variables().empty(), "Need to have member variables");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment