Next: , Previous: , Up: ccnames   [Contents][Index]


A.2 Tables of methods for struct types

The macros for the “table of methods known functions” define an API to implement a table of methods in a data struct: every instance of the struct type is meant to hold a pointer to a statically allocated struct which in turn holds pointers to method functions. The following macros are defined in the header file ccnames.h.

Macro: ccname_table_type (STRUCT_TYPE)
Macro: ccname_table_type (STRUCT_TYPE, VARIANT)

Given a struct type name and an optional variant specification: expand into the name of the methods table type for the struct type.

Macro: ccname_table (STRUCT_TYPE)
Macro: ccname_table (STRUCT_TYPE, VARIANT)

Given a struct type name and an optional variant specification: expand into the name of the methods table for the struct type.

Macro: ccname_method_type (STRUCT_TYPE, VARIANT, METHOD_NAME)

Given a struct type name, an optional variant specification, and a method name: expand into the type name of that variant of the method function for the struct type.

Macro: ccname_method (STRUCT_TYPE, METHOD_NAME)
Macro: ccname_method (STRUCT_TYPE, VARIANT, METHOD_NAME)

Given a struct type name, an optional variant specification, and a method name: expand into the name of that variant of the method for that struct type.

An example of methods table implementation for struct types:

#include <ccexceptions.h>
#include <ccnames.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct my_coords_t                      my_coords_t;
typedef struct ccname_table_type(my_coords_t)   ccname_table_type(my_coords_t);

typedef void ccname_method_type(my_coords_t, print) (my_coords_t * S, FILE * stream);

struct my_coords_t {
  ccname_table_type(my_coords_t) const * methods;
  double        X;
  double        Y;
};

struct ccname_table_type(my_coords_t) {
  ccname_method_type(my_coords_t, print) * print_rec;
  ccname_method_type(my_coords_t, print) * print_pol;
};

static void
ccname_method(my_coords_t, print_rec) (my_coords_t * S, FILE * stream)
{
  fprintf(stream, "X=%f, Y=%f\n", S->X, S->Y);
}

static void
ccname_method(my_coords_t, print_pol) (my_coords_t * S, FILE * stream)
{
  double        RHO   = hypot(S->X, S->Y);
  double        THETA = atan2(S->Y, S->X);

  fprintf(stream, "RHO=%f, THETA=%f\n", RHO, THETA);
}

static ccname_table_type(my_coords_t) const ccname_table(my_coords_t) = {
  .print_rec    = ccname_method(my_coords_t, print_rec),
  .print_pol    = ccname_method(my_coords_t, print_pol)
};

void
ccname_init(my_coords_t, rec) (my_coords_t * S, double X, double Y)
{
  S->methods = &ccname_table(my_coords_t);
  S->X = X;
  S->Y = Y;
}

void
ccname_init(my_coords_t, pol) (my_coords_t * S, double RHO, double THETA)
{
  S->methods = &ccname_table(my_coords_t);
  S->X = RHO * cos(THETA);
  S->Y = RHO * sin(THETA);
}

Next: , Previous: , Up: ccnames   [Contents][Index]

This document describes version 0.3.0-devel.3 of CCStructs.