    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Metaclasses and Reflection in C++</title>
        <link>https://members.accu.org/index.php/journals/428</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #45 - Oct 2001 + Programming Topics + Design of applications and programs</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c159/">45</a>
                    (5)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c67/">Design</a>
                    (236)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c159-65-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c159+65+67/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Metaclasses and Reflection in C++</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 October 2001 17:46:07 +01:00 or Fri, 26 October 2001 17:46:07 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>Over the last two years I've held several tutorials on
meta-classes and reflection in C++. I use the term reflection here
in its original sense, &quot;looking back to oneself&quot;, nowadays
sometimes called introspection. The more general process to allow
modifications at class level at run-time is the old task to provide
a meta-level, but is today sometimes (mis-)called &quot;behavioural
reflection&quot; or &quot;structural reflection&quot;.</p>
<p>In some sense this article presents work in progress, though
it's been going on for nearly ten years now. It's not the
definitive meta-object protocol for C++, but more a presentation of
lesser-known C++ techniques to solve some specific design
problems.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id=
"d0e24"></a>Introduction</h2>
</div>
<p>C++ is a strongly typed compiler language. Though not as
strongly typed as ADA, a C++ compiler will complain if you try to
assign an object of one type to an object of another type (if there
is no acceptable conversion). Obviously, this requires that the
compiler know all available types. More specifically, all classes
must be known at compile-time<sup>[<a name="d0e29" href=
"#ftn.d0e29" id="d0e29">1</a>]</sup>. But sometimes, it would be
quite handy to add new classes at runtime. And in some application
domains, this is absolutely necessary.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e33" id="d0e33"></a>A simple
story</h2>
</div>
<p>Let's look at a simple example: Susan, the manager of a local
bookstore, wants to expand into the Internet. So she asks you to
write a simple program for an Internet bookshop. No problem for
you. Part of your solution will probably look like the class model
in Figure 1.</p>
<div class="figure"><a name="d0e38" id="d0e38"></a>
<p class="title c2">Figure 1. Simple Shop Model</p>
<div class="mediaobject"><img src="/var/uploads/journals/resources/metaclasses_fig_1.jpg"
alt="Simple Shop Model"></div>
</div>
<p>The implementation of this in C++ is straightforward. Here is
the Book class:</p>
<pre class="programlisting">
class Book
{
public:
  Book(const string &amp; author_,
    const string &amp; title_,
    const string &amp; publisher_,
    double price_,
    double weight_);
  string getName()
  {
    string name;
    name = author + &quot;: &quot; + title;
    return name.substr(0, 40);
  }
  double getPrice();
  double getWeight();
private:
  string author, title, publisher;
  double price, weight;
};
</pre>
<p>Your solution works, Susan is happy, and all is fine for a
while... But changes come on the Web in Internet time: the bookshop
is a success and Susan decides to sell CDs as well. So you have to
change your program. With object orientation, you can do this quite
easily and your modified class model will look like Figure. 2.</p>
<div class="figure"><a name="d0e50" id="d0e50"></a>
<p class="title c2">Figure 2. Product Model</p>
<div class="mediaobject"><img src="/var/uploads/journals/resources/metaclasses_fig_2.jpg"
alt="Product Model"></div>
</div>
<p>As you probably guessed, this was only the beginning. Some time
later, Susan wants to sell Pop music accessories like T-shirts,
posters, etc. as well.</p>
<p>Now it is clear that it is not acceptable to modify the source
code of your program every time a new product category is
introduced. So you start to think about the actual requirements,
and find that you need to provide different interfaces for your
<tt class="literal">Product</tt> class (Figure. 3): A simple
interface for <tt class="literal">ShoppingCart</tt> providing
<tt class="literal">getName()</tt>, <tt class=
"literal">getPrice()</tt>, and <tt class=
"literal">getWeight()</tt>. This is what you already have. Then you
need a different interface for a general search
machine<sup>[<a name="d0e75" href="#ftn.d0e75" id=
"d0e75">2</a>]</sup>, which must provide information like:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>what is the actual class of the object</p>
</li>
<li>
<p>what attributes does that class have</p>
</li>
<li>
<p>what are the actual values of these attributes for the
object.</p>
</li>
</ul>
</div>
<p>This is a classic reflection interface that gives you
information about the properties of classes and objects. But you
also need a third interface for product maintenance that allows you
to define new product classes, specify the attributes for them,
create instances of these classes, and set the attribute values of
these instances. Such an interface is called a &quot;Meta-Object
Protocol (MOP)&quot; and thoroughly discussed in [<a href=
"#Kiczales-">Kiczales-</a>]. The reflection protocol is a subset of
such a MOP.</p>
<div class="figure"><a name="d0e94" id="d0e94"></a>
<p class="title c2">Figure 3. A Better Model</p>
<div class="mediaobject"><img src="/var/uploads/journals/resources/metaclasses_fig_3.jpg"
alt="A Better Model"></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e100" id="d0e100"></a>Meta Classes
for C++</h2>
</div>
<p>What is the meaning of &quot;Meta-Object Protocol&quot;? Well,
meta-information is information about something else seen from a
level beyond - a meta-level. So, information about the attribute
values of an object, say someBook.author, is information on the
object level. But information about the properties of the object
itself, about its attributes, its structure, etc. is
meta-information.</p>
<p>In C++, this information is captured in the class definition for
the object, so the class is a meta-object. And in C++, you have all
the functionality of a MOP at class level - which is at development
time. But that level is not available at runtime: You cannot
manipulate classes like objects, you cannot add new classes at
runtime. The idea of a MOP is to collapse the meta-level (classes)
and the object level (objects); i.e. make the class definitions
normal objects and the object properties are normal attribute
values of the class definitions that can be manipulated at
runtime.</p>
<p>While languages like CLOS or Smalltalk provide this combined
level directly, C++ as a strongly typed compiled language has no
such features. So, what can you do about it? The typical solution
is to provide a MOP yourself, as proposed e.g. in [<a href=
"#Coplien">Coplien</a>] or [<a href=
"#Buschmann-">Buschmann-</a>].</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e115" id="d0e115"></a>MOP
Overview</h2>
</div>
<p>For simplicity, we ignore methods for now, so our MOP must
provide:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>definition of new classes</p>
</li>
<li>
<p>adding attributes to classes</p>
</li>
<li>
<p>querying attributes of classes</p>
</li>
<li>
<p>creating objects</p>
</li>
<li>
<p>querying the class of an object</p>
</li>
<li>
<p>setting attribute values of an object</p>
</li>
<li>
<p>querying attribute values of an object</p>
</li>
<li>
<p>deleting objects</p>
</li>
</ul>
</div>
<p>If you use an old rule of OO design, you take all the nouns of
the above requirements and make classes out of them. When you think
about the &quot;attributes&quot; and &quot;values&quot; you have to decide whether they
are typed. As the underlying language C++ is typed this should be
mirrored in your design.</p>
<p>Another question is about inheritance support. For our example
with the Internet shop and a product hierarchy this would probably
quite useful. So, a first class model is shown in Figure 4.</p>
<div class="figure"><a name="d0e149" id="d0e149"></a>
<p class="title c2">Figure 4. MOP Class Model</p>
<div class="mediaobject"><img src="/var/uploads/journals/resources/metaclasses_fig_4.jpg"
alt="MOP Class Model"></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e155" id="d0e155"></a>Type</h2>
</div>
<p>While it is useful to go top-down for a general overview, it's
easier to start with the simple basic things for the details. So
we'll first look at <tt class="literal">Type</tt>.</p>
<p>The main purpose of <tt class="literal">Type</tt> is to
distinguish different kinds of <tt class="literal">Attribute</tt>s.
For this, a simple <tt class="literal">enum</tt> would suffice. But
the idea of types is to have different kind of <tt class=
"literal">Values</tt> for different <tt class="literal">Type</tt>s,
so the <tt class="literal">Type</tt> should create new <tt class=
"literal">Values</tt>. So we put the <tt class="literal">enum</tt>
inside the <tt class="literal">Type</tt> class, provide the
<tt class="literal">newValue()</tt> method, and get the interface
shown in Figure. 4.</p>
<p>Now for implementation. Although we don't look closely at
<tt class="literal">Value</tt> right now, if we have different
kinds of values we probably need some base class for them. Let's
call it &quot;<tt class="literal">BaseValue</tt>&quot;, and <tt class=
"literal">newValue()</tt> can just return a pointer to <tt class=
"literal">BaseValue</tt>.</p>
<p>Now we know what to create, but how? While there are several
patterns to implement polymorphic creation [4], the simplest one
for our purposes is probably the Prototype, which can be easily
implemented with a simple static vector<sup>[<a name="d0e211" href=
"#ftn.d0e211" id="d0e211">3</a>]</sup>.</p>
<p>Now we have everything to implement the entire class:</p>
<pre class="programlisting">
class Type { public: enum TypeT {stringT, intT, doubleT, unknownT}; explicit Type(TypeT typeId_) : typeId(typeId_) {} BaseValue * newValue() const { return prototypes[typeId]-&gt;clone(); } TypeT getType() const { return typeId; } static void init(); { prototypes[stringT] = new Value&lt;string&gt;(&quot;&quot;); prototypes[intT] = new Value&lt;int&gt;(0); prototypes[doubleT] = new Value&lt;double&gt;(0); } private: TypeT typeId; static vectorBaseValue * prototypes; }; vector&lt;BaseValue *&gt; Type::prototypes(Type::unknownT);
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e219" id=
"d0e219"></a>Attribute</h2>
</div>
<p>As we have decided to create new <tt class="literal">Value</tt>s
through <tt class="literal">Type</tt>, <tt class=
"literal">Attribute</tt> contains only a name and type, so here is
its implementation:</p>
<pre class="programlisting">
class Attribute { public: Attribute(const string &amp; name_, Type::TypeT typeId) : name(name_), type_(typeId) {} const string &amp; getName() const { return name; } Type getType() const { return type_; } private: string name; Type type_; };
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e235" id="d0e235"></a>Classes</h2>
</div>
<p>We can now finish the class (meta-) level of our model by
looking at <tt class="literal">Class</tt> itself. As multiple
inheritance is probably not an issue for our purposes, we have just
one pointer to a base class (which can be 0). The more important
question is the attribute list: Should it hold only the attributes
defined for this class or should it include all inherited
attributes? While for the actual object value access a complete
list is more useful (and much faster), for class maintenance it
might be important to know which attribute was defined in which
class. So we just keep both. For the complete list, the order might
be significant: should the own attributes come first or the
inherited ones? In most illustrations the inherited attributes come
first, so we keep this order as well.</p>
<p>What happens if the name of an attribute is the same as the name
of an inherited attribute? As C++ allows it, we can allow it as
well (saving us some extra effort to check this), but in this case
we must guarantee that on lookup of an attribute by name we get the
most derived attribute. So, <tt class=
"literal">findAttribute()</tt> must do a reverse search. What shall
we return from <tt class="literal">findAttribute()</tt>? The STL
way would be to return an iterator, but for applications with GUIs
(to create new objects and assign values to its attributes based on
selection lists) an index-based access to the attributes will be
more appropriate. So <tt class="literal">findAttribute()</tt>
returns an index and <tt class="literal">getAttribute()</tt> takes
an index and returns an Attribute. So the Attribute lists need to
be indexed containers, so we choose vectors for them.</p>
<p>A major purpose of <tt class="literal">Class</tt> is to create
Objects from it, so it has a method <tt class=
"literal">newObject()</tt> which returns a pointer to an Object. Do
we need to keep a repository with references to all created
objects? For a full reflection interface we should do this. But for
actual applications this is almost never useful, as objects of the
same class are created for completely different purposes. But do we
need the repository for internal use? It depends on what we want to
do with objects after they were created. This leads directly to
another important decision: What do we do with already existing
objects if we add a new attribute to a class? One option is to add
this attribute to all existing objects and assign it a default
value. The other option is to leave these existing objects and add
the new attribute only to new objects. This leads to differently
structured objects of the same class at the same time, and then we
must add some version information to the objects. But there is a
third option: To forbid the modification of a class definition once
an instance of that class was created. This is the easiest option,
so we adopt it for our MOP and add a flag <tt class=
"literal">definitionFix</tt>. With that flag, we can skip the
object repository.</p>
<p>A last design question is when to add the attributes: At
creation time of a class definition (through the constructor) or
later (with a member function)? For different applications both
options might be useful, so we'll provide two constructors and
<tt class="literal">addAttribute()</tt>.</p>
<p>Now you can implement this<sup>[<a name="d0e275" href=
"#ftn.d0e275" id="d0e275">4</a>]</sup>:</p>
<pre class="programlisting">
class ClassDef { //typedefs Container, Iterator for attributes public: ClassDef(ClassDef const * base, const string &amp; name_) : baseClass(base), name(name_), definitionFix(false) { baseInit(); effectiveAttributes.insert(effectiveAttributes.end(), ownAttributes.begin(), ownAttributes.end()); } template &lt;typename iterator&gt; ClassDef(ClassDef const * base, const string &amp; name_, iterator attribBegin, iterator attribEnd) : baseClass(base), name(name_), ownAttributes(attribBegin, attribEnd), definitionFix(false) { baseInit(); effectiveAttributes.insert(effectiveAttributes.end(), ownAttributes.begin(), ownAttributes.end()); } string getName() const; Object * newObject() const { definitionFix = true; return new Object(this); } AttrIterator attribBegin() const; AttrIterator attribEnd() const; Attribute const &amp; getAttribute(size_t idx) const; void addAttribute(const Attribute &amp;); size_t getAttributeCount() const; size_t findAttribute(string const &amp; name) const { // this does a reverse search to find the most derived AttributeContainer::const_reverse_iterator i; for (i = effectiveAttributes.rbegin(); i != effectiveAttributes.rend(); ++i) { if (i-getName() == name) { return distance(i, effectiveAttributes.rend()) - 1; } } return getAttributeCount(); } private: void baseInit() { if (baseClass) { baseClass-definitionFix = true; copy(baseClass-&gt;attribBegin(), baseClass-&gt;attribEnd(), back_inserter&lt;AttributeContainer&gt;(effectiveAttributes)); } } ClassDef const * const baseClass; string name; AttributeContainer ownAttributes, effectiveAttributes; mutable bool definitionFix; };
</pre>
<div class="figure"><a name="d0e281" id="d0e281"></a>
<p class="title c2">Figure 5. Value Model</p>
<div class="mediaobject"><img src="/var/uploads/journals/resources/metaclasses_fig_5.jpg"
alt="Value Model"></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e287" id="d0e287"></a>Values</h2>
</div>
<p>Before we can design <tt class="literal">Object</tt>, we have to
think about <tt class="literal">Value</tt>. We need a common
interface to manage them, which we already called <tt class=
"literal">BaseValue</tt>. But what interface do we need? The whole
idea of <tt class="literal">Value</tt> is to store values, so we
need a <tt class="literal">set()</tt> function. What parameter? The
only thing we have is <tt class="literal">BaseValue</tt>, so that's
the parameter type. Pass by value, by reference, or by pointer?
Definitely not by value, as <tt class="literal">BaseValue</tt> is
only an interface. On the other hand, what you pass is a value, so
the parameter passing should be by value to let you pass
temporaries. So one option would be to pass by <tt class=
"literal">const</tt> reference. But though this helps for the
problem at hand, it doesn't cure the fundamental problem: you
should have a value, but all you have is a polymorphic interface.
The real solution here is the <span class=
"emphasis"><em>pimpl</em></span> idiom, also known as <span class=
"emphasis"><em>Cheshire Cat</em></span>, <span class=
"emphasis"><em>Envelope/Letter</em></span>, or more generally
<span class="emphasis"><em>Handle/Body</em></span>. So we add a
handle class, name it <tt class="literal">Value</tt>, and look at
it later again. For now we're still at <tt class=
"literal">BaseValue</tt>.</p>
<p>We now have <tt class="literal">set(Value)</tt>, so what about
<tt class="literal">get()</tt>? The return type of <tt class=
"literal">get()</tt> would be <tt class="literal">Value</tt>, and
the implementation would look like:</p>
<pre class="programlisting">
Value BaseValue::get() { return *this; // calls Value(BaseValue const &amp;) }
</pre>
<p>But that we can do directly, so <tt class="literal">get()</tt>
doesn't make much sense. What other <tt class=
"literal">BaseValue</tt> functions do we need? Values must be
copied, so we add <tt class="literal">clone()</tt>. That's all what
we really need from a value, but we add <tt class=
"literal">asString()</tt> for convenience<sup>[<a name="d0e364"
href="#ftn.d0e364" id="d0e364">5</a>]</sup>.</p>
<pre class="programlisting">
class BaseValue { public: virtual ~BaseValue(){} virtual BaseValue * clone() const = 0; virtual string asString() const = 0; // fromString() virtual void set(Value const &amp; v) = 0; // no get()! private: // Type info };
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e372" id=
"d0e372"></a>RealValue</h2>
</div>
<p>Now, as we have the interface, what about the implementation? We
need values for <tt class="literal">int</tt>, <tt class=
"literal">double</tt>, <tt class="literal">string</tt>, etc. And an
<tt class="literal">int</tt> value must hold an <tt class=
"literal">int</tt>, a <tt class="literal">double</tt> value a
<tt class="literal">double</tt>, etc. This looks like an
opportunity for a template. So, let's define <tt class=
"literal">RealValue&lt;T</tt>&gt;, derive it from <tt class=
"literal">BaseValue</tt>, implement the inherited interface, and
we're nearly done. But as <tt class=
"literal">RealValue&lt;T&gt;</tt> is just a wrapper around
<tt class="literal">T</tt> with some additional functionality, but
essentially still a <tt class="literal">T</tt>, we should provide
conversion in both directions, by providing a converting
constructor and a conversion operator.</p>
<pre class="programlisting">
template &lt;typename PlainT&gt; class RealValue : public BaseValue { public: RealValue(PlainT v) : val(v) {} RealValue * clone() const { return new RealValue(*this); } string asString() const { ostringstream os; os &lt;&lt; val; return os.str(); } operator PlainT() const // conversion to plain type { return val; } RealValue&lt;PlainT&gt;::set(Value const &amp; v) { val = v.get&lt;PlainT&gt;(); } private: PlainT val; };
</pre>
<p>A note about <tt class="literal">RealValue</tt>: As we have
conversion in both directions, we can use <tt class=
"literal">RealValue&lt;T&gt;</tt> like <tt class=
"literal">T</tt>:</p>
<pre class="programlisting">
RealValueint i = 1; int j = i; RealValuedouble d = i + 5.2 / (i*2); cout &lt;&lt; d &lt;&lt; endl;
</pre>
<p>Nearly: the following doesn't work:</p>
<pre class="programlisting">
RealValue&lt;string&gt; name, author = &quot;Bjarne&quot;, title = &quot;The C++ PL&quot;; name = author + &quot;: &quot; + title; cout &lt;&lt; name &lt;&lt; endl;
</pre>
<p>The reason is that the compiler only applies one user-defined
conversion, but for string literals, you need two: from char const
* to string, and from string to <tt class=
"literal">RealValue&lt;string&gt;</tt>. If you want to work with
<tt class="literal">RealValue&lt;string&gt;</tt> outside the MOP,
you should define a specialization:</p>
<pre class="programlisting">
template &lt;&gt; class RealValue&lt;string&gt; : public BaseValue, public string { public: RealValue(string const &amp; s) : string(s) {} RealValue(char const * s) : string(s) {} RealValue() {} RealValue * clone() const { return new RealValue(*this); } string asString() const { return static_cast&lt;string&gt;(*this); } // no operator string(), conversion to base automatically void set(Value const &amp; v) { string::operator=(v.get&lt;string&gt;()); } };
</pre>
<p>Note: Actually, its not really clean to derive <tt class=
"literal">RealValue&lt;string&gt;</tt> from <tt class=
"literal">std::string</tt>, but as long as you don't delete a
<tt class="literal">RealValue&lt;string&gt;</tt> through a pointer
to <tt class="literal">string</tt>, it will work.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e456" id="d0e456"></a>Value
handle</h2>
</div>
<p>Now back to the handle class <tt class="literal">Value</tt>. As
a handle class, it contains its body and cares for it. Its main job
is to adopt/create and to delete its body. And it mirrors the
interface of the body and forwards all messages. But it should also
be a real value class, thus providing default and copy constructor
and assignment. But how do we implement the default constructor? As
we don't know what type to create, we must create an empty handle
without a body and check before forwarding if we actually have
something to forward to. The assignment is essentially the
<tt class="literal">set()</tt>, so we skip the <tt class=
"literal">set()</tt>.</p>
<p>Now let's come back to the <tt class="literal">get()</tt>. Of
course, to return a <tt class="literal">Value</tt> or <tt class=
"literal">BaseValue</tt> doesn't make sense. What about returning
the <tt class="literal">RealValue</tt> or even the wrapped
underlying value? That would be really useful, but for that we have
to tell <tt class="literal">get()</tt> what we want as return type.
So <tt class="literal">get()</tt> becomes a member template and so
can return whatever is inside the <tt class=
"literal">RealValue</tt>.</p>
<pre class="programlisting">
class Value // Value handle { public: Value(BaseValue const &amp; bv) : v(bv.clone()) {} Value(Value const &amp; rhs) : v(rhs.v ? rhs.v-clone() : 0) {} explicit Value(BaseValue * bv = 0) : v(bv) {} ~Value() { delete v; } Value &amp; operator=(const Value &amp; rhs) { // this is not a typical pimpl assignment, but a set() if (v) { if (rhs.v) { // fine, all v's exist v-&gt;set(rhs); } else { // the other v doesn't exist, so we must delete our own :-( BaseValue * old = v; v = 0; delete old; } } else { // we don't have a v, so just copy the other v = (rhs.v ? rhs.v-clone() : 0); } return *this; } template &lt;typename PlainT&gt; PlainT get() const { if (v) { RealValue&lt;PlainT&gt; const &amp; rv = dynamic_castRealValuePlainT const &amp;(*v); return rv; // uses conversion operator } else { return PlainT(); } } std::string asString() const { if (v) { return v-&gt;asString(); } else { return string(); } } private: BaseValue * v; }; 
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e495" id="d0e495"></a>Object</h2>
</div>
<p>Finally we come to <tt class="literal">Object</tt>. Now, as we
have everything else, an <tt class="literal">Object</tt> is mainly
a container for its attribute values. To ease implementation, we
will structurally mirror the attribute container in the class
definition, so we use a vector. As we have so much effort invested
in our <tt class="literal">Value</tt> handle, it would make sense
to store that in the vector. But for future extensions it will be
easier to have the <tt class="literal">BaseValue</tt> pointers
directly available. The constructor will create the values through
the types of the attributes, so the only constructor takes a
<tt class="literal">ClassDef*</tt>. To set and get the values for
the attributes, we provide two options: to specify the attribute by
name and also by index. For reflection purposes (as well as for
internal implementation) we need a pointer to the class definition,
but then we have it all:</p>
<pre class="programlisting">
class Object { public: explicit Object(ClassDef const * class_) : myClass(class_), values(class_-&gt;getAttributeCount()) { buildValueList(); } ClassDef const &amp; instanceOf() const { return *myClass; } Value getValue(size_t attribIdx) const { return *values[attribIdx]; // calls Value(BaseValue &amp;) } Value getValue(string const &amp; attribName) const { size_t idx = instanceOf()-&gt;findAttribute(attribName); // should check for not found return getValue(idx); } void setValue(size_t idx, Value const &amp; v) { values[idx]-&gt;set(v); } void setValue(string const &amp; attribName, Value const &amp;v) { size_t idx = instanceOf()-&gt;findAttribute(attribName); // should check for not found setValue(idx, v); } private: typedef vector&lt;BaseValue *&gt; ValueContainer; void buildValueList() { ClassDef::AttrIterator a; ValueContainer::iterator i = values.begin(); for (a = instanceOf()-&gt;attribBegin(); a != instanceOf()-&gt;attribEnd(); ++a, ++i) { *i = a-&gt;getType().newValue(); } } ClassDef const * const myClass; ValueContainer values; };
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e517" id="d0e517"></a>Next
Article</h2>
</div>
<p>This article has described the design and implementation of a
meta-object layer for C++. A subsequent article will continue this
discussion by demonstrating how these techniques can be used to
solve the design problems found in the Internet bookshop
example.</p>
<p>If you have comments on these techniques, or proposals how the
problems could be solved completely differently, or if you find
errors in this article, I would really appreciate your feedback to
<tt class="email">&lt;<a href=
"mailto:dv@vollmann.ch">dv@vollmann.ch</a>&gt;</tt>.</p>
<p>Further source code to illustrate the implementation of the
ideas in this article can be found at <a href=
"http://www.vollmann.com/download/mop/index.html" target=
"_top">http://www.vollmann.com/download/mop/index.html</a>.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e532" id="d0e532"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Kiczales-" id="Kiczales-"></a>
<p class="bibliomixed">[Kiczales-] Gregor Kiczales, Jim des
Rivi&egrave;res, Daniel G. Bobrow: &quot;The Art of the Metaobject
Protocol&quot;, MIT Press 1991, ISBN 0-262-61074-4</p>
</div>
<div class="bibliomixed"><a name="Coplien" id="Coplien"></a>
<p class="bibliomixed">[Coplien] James O. Coplien: &quot;Advanced C++
Programming Styles And Idioms&quot;, Chapters 8-10, Addison-Wesley,
1992, ISBN 0-201-54855-0</p>
</div>
<div class="bibliomixed"><a name="Buschmann-" id="Buschmann-"></a>
<p class="bibliomixed">[Buschmann-] Frank Buschmann, Regine
Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal:
&quot;Pattern-Oriented Software Architecture: A System of Patterns&quot;,
Wiley 1996, ISBN 0-471-95869-7</p>
</div>
<div class="bibliomixed"><a name="Gamma-" id="Gamma-"></a>
<p class="bibliomixed">[Gamma-] Erich Gamma, Richard Helm, Ralph
Johnson, John Vlissides: &quot;Design Patterns&quot;, Addison-Wesley 1994,
ISBN 0-201-63361-2</p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e29" href="#d0e29" id=
"ftn.d0e29">1</a>]</sup> I will not elaborate on differences
between type and class.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e75" href="#d0e75" id=
"ftn.d0e75">2</a>]</sup> The idea of the search machine is to have
a batch process that queries all objects about its attribute values
and create an own internal index from that information.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e211" href="#d0e211" id=
"ftn.d0e211">3</a>]</sup> actually, a simple array would suffice,
as its size is fix and known at compile time. But for future
extensions a vector is more flexible.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e275" href="#d0e275" id=
"ftn.d0e275">4</a>]</sup> As class is a reserved word in C++, and I
don't like identifiers to differ only in case from others I have
chosen ClassDef here.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e364" href="#d0e364" id=
"ftn.d0e364">5</a>]</sup> <tt class="literal">fromString()</tt>
would also be useful, but we omit it here.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
