This is the mail archive of the mailing list for the GSL project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: containers tentative design summary

On Fri, 2009-10-23 at 14:58 +0100, Brian Gough wrote: 
> I think this is an interesting example.  How would these two classes
> work in practice in C? For example, how would one pass a non-const
> matrix (taken as a view of a non-const multi-array) to a function
> taking a const matrix argument.  Dealing with the interaction between
> const and non-const arguments is a fundamental issue.

> The challenge for any scheme is getting reasonable const behavior in
> C.  If that problem can be solved better then everything else follows
> more easily.

Ok. The attachment is the obvious solution. I don't want to have
theological wars about this, but it seems to me like it is
the "C way". Let's debate.

G. Jungman

#include <stdlib.h>

/* The union guarantees that the structs are aligned, in C99.
 * In C90, standard does not discuss the issue, but all
 * compilers known to man align them anyway. The C99
 * guarantee seems to be an attempt to standardize
 * that behaviour.
 * The union type is never actually used, unless somebody
 * can think of a reason to use it...
union gsl_vector_union_t
  struct gsl_vector_struct_t
    double * data;
    size_t   size;
    int      stride;
  } as_vector;

  struct gsl_const_vector_struct_t
    const double * data;
    size_t   size;
    int      stride;
  } as_const_vector;

typedef  struct gsl_vector_struct_t        gsl_vector;
typedef  struct gsl_const_vector_struct_t  gsl_const_vector;

void gsl_some_typical_function(const gsl_vector * v)
  /* do something which might twiddle[] */

void gsl_some_typical_const_function(const gsl_const_vector * v)
  /* do something which does not twiddle[] */

int main()
  gsl_vector v;
  gsl_const_vector cv;

  /* might be twiddling[] */

  /* claims not to twiddle[] */

  /* claims not to twiddle[] */
  gsl_some_typical_const_function((const gsl_const_vector *) &v);

  /* a misuse; but this sort of thing can never be prevented anyway */
  gsl_some_typical_function((const gsl_vector *) &cv);

  return 0;

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]