2

ノードが

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

私のデータ構造には、戻り値の型を持つ多くの関数がありstruct node *、ユーザーにこの型を不透明として扱いたいと思っています。リンクされたリストの例では、そのような関数はたとえばget_next(struct node<T> *n)またはinsert_after(struct node<T> *x, struct node<T> *y). 非常に少数の関数、つまりnodes を割り当てたり、フィールドを取得/設定したりする関数だけdataが、 について何かを知る必要がありTます。

「無視」して、ユーザーが気にする必要のない関数Tのようなものとのみ対話できるようにする、より良い方法はありますか? C から来る私の直感的な反応は、 との間でキャストすることですが、それはあまりエレガントに聞こえません。typedef struct node * opaque_handleTvoid*

編集: CygnusX1 のコメントは、私があまりにも多くの保証を回避しようとしていると同時に、型システムにあまりにも多くの保証を求めていることを確信させました。キャスティングと間接化を犠牲にして、 Tbe let back に戻ります。void *

4

2 に答える 2

1

While you don't care about what T is, you most like want to differenciate it from a different type - say U, don't you? You probably want the following to raise an error:

node<T>* elem1 = ...
node<U>* elem2 = ...
elem1 = elem2

There are a few ways to make your code simpler without sacrificing the type checking or run-time perforamce:

  • If you use C++11, consider using auto instead of explicitly naming the type when using your functions
  • If node<T> is very common in your code, you can set a global-scope typedef

Also note, that in the context of node<T> definition, using a plain node (without template arguments) is allowed.

If you really want to hide the contents of the node, consider implementing the pimpl pattern as suggested by mvidelgauz.

于 2016-06-25T17:50:01.820 に答える