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

Myron Alexander someone at somewhere.com
Sun May 27 13:33:23 PDT 2007


Hello.

I currently have a struct for named parameters called NamedParameter and 
this is defined as such:

struct NamedParameter {
    char[] name;
    Box    value;

    char[] toString () {
       return "(" ~ name ~ ": " ~ value.toString () ~ ")";
    }

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

       // I have used a static if instead of static assert as the assert 
cannot
       // resolve and output the 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 ~
             ").");
       }

       NamedParameter m_np;

       m_np.name  = name;

       static if (is (T == Box)) {
          m_np.value = value;

       } else {
          m_np.value = box (value);
       }

       return m_np;
    }
}


The problem with this struct is that the name, and value fields are 
public and I want them private so the user is forced through the opCall. 
My reason for this is that I want all the validations done on 
initialization instead of having to be done whenever I use the values. 
(These validations are not in the above code).

The only way to make the fields private is to have a class so I would 
like to build my class to work as a value object in the same way that 
structs do but with information hiding.

How can I do this?

Thanks ahead,

Myron.


More information about the Digitalmars-d-learn mailing list