I've been reading a bit about what metaclasses are, but I would like to know if they can be achieved in C++.
I know that Qt library is using MetaObjects, but it uses an extension of C++ to achieve it. I want to know if it is possible directly in C++.
Thanks.
If the working definition of metaclass is "a language entity whose instantiations are themselves classes," then generics are metaclasses in C++:
#include <iostream>
using namespace std;
template <typename T>
class Meta {
public:
Meta(const T&init) : mData(init) {}
// ...
private:
T mData;
};
int main(int, char **) {
cout << "The size of Meta<double> is " << sizeof(Meta<double>) << endl ;
return 0;
}
The use of Meta<double> in the antepenultimate line compels the compiler to instantiate the Meta<double> class; the sizeof operator operates upon Meta, thus demonstrating that this is not simply semantic sugar and that the class has been instantiated. The program is complete even though no objects of type Meta are instantiated.
C++ Doesn't have built-in support for meta-classes (not in the Python/Objective-C way), however you can manually mimic the behavior of meta-classes. The basics are pretty simple, you create an extra class with a longer lifespan (Singleton, static object or the Construct On First Use Idiom) that is able to create and manipulate it's corresponding class. (In Objective-C the meta-class generally contains 'static' member variables, the memory allocation/deallocation routines et cetera).
What Qt has done is, they took the concept of meta-classes and modified it so that they can support some form of Reflection (and RTTI on systems that don't support it). Implementing this will require either a lot of macro magic or a custom compiler (such as they've chosen to use).
Generally though, most of the features a regular meta-class provides are already provided by the C++ language; just in a different form. And really, the only reason you'd want meta-objects would be for reflection purposes, there are different ways to implement reflection in C++ as outlined in this document.
Besides that, if you're really set on a Objective-C-style meta-class system, I'm not aware of any libraries that do that but there might very well be. On the other hand, rolling your own shouldn't be that difficult either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With