mercredi 29 juin 2016

Opaque pointer to struct with template members

Suppose I'm building a linked list (the real data structure is completely different, but a linked list suffices for the question) whose nodes look like

template <typename T>
struct node
{
  struct node<T> *next;
  T data;
};

For my data structure, I have a lot of functions with return type struct node *, and I want the user to treat this type as opaque. In the linked list example, such a function could be for example get_next(struct node<T> *n) or insert_after(struct node<T> *x, struct node<T> *y). Only very few functions, namely those that allocate nodes or get/set their data field, need to know anything about T.

Is there a nicer way to "ignore T" and let the user interact only with something like a typedef struct node * opaque_handle for those functions that don't ever have to care about T? My gut reaction, coming from C, is just to cast to and from void*, but that doesn't sound very elegant.

Edit: CygnusX1's comment has convinced me that I'm asking for too many guarantees from the type system at the same time that I'm trying to circumvent too many of those guarantees. I will fall back to letting T be void * at the cost of casting and indirection.

Aucun commentaire:

Enregistrer un commentaire