Q: How can I make a class act like a value type (such as struct)

Myron Alexander someone at somewhere.com
Sun May 27 14:25:28 PDT 2007


Regan Heath wrote:
> What 'value object' behaviour do you want?  As in, how are you using these types?  Example please :)  Something like this...
> 
> NamedParameter p("test",5);
> NamedParameter q;
> 
> q = p;
> 
> In the above, is it that you want q to be a copy of p as opposed to both p and q referring to the same object?
> 

Regan,

The above is one aspect of what I meant as a value object but my manner 
of use does not need it. I am more concerned with storage and I want my 
class to be allocated on the stack rather than on the heap so that the 
GC does not have to bother with it.

If such a thing can't be done, then I am happy with GC'd references.

This is a simple example of how it is used (np is an alias for 
NamedParameter):

cu.execute (
   "insert into atable values (:id, :name, :balance)",
   np("id",4), np("name","Fourth Person"), np("balance",999.99));


I've done a conversion and this is my latest version:

class NamedParameter {

    private this (char[] name, Box value) {
       m_name  = name;
       m_value = value;
    }

    static NamedParameter opCall(T) (char[] name, T value) {

       // I have used a static if instead of static assert as the assert 
cannot
       // resolve name and value.name. I would prefer a compile time error.
       static if (is (T == NamedParameter)) {
          throw new SqlProgrammingException (
             "Invalid named parameter value. The value of a named 
parameter may "
             "not be a named parameter. Error on parameter (" ~ name ~
             ") trying to nest parameter (" ~ value.name ~
             ").");
       }

       Box v;

       static if (is (T == Box)) {
          /* Unnest the innermost value.
           */
          v = value;
          while (v.type == typeid (Box)) {
             v = unbox!(Box)(v);
          }

       } else {
          v = box (value);
       }

       return new NamedParameter (name, v);
    }

    char[] name () {
       return m_name;
    }

    Box value () {
       return m_value;
    }

    char[] toString () {
       return "(" ~ m_name ~ ": " ~ m_value.toString () ~ ")";
    }

    private char[] m_name;
    private Box    m_value;
}

Regards,

Myron.


More information about the Digitalmars-d-learn mailing list