I am lazy I don't want to write the same code twice, so how can I avoid it in this case? I have nodes in a tree some of them has a member _key like this:
struct node_base {
virtual void foo()=0;
virtual ~node_base() {}
}
template<typename Key>
struct node_key: public node_base {
node_key(Key k): _key(k) {}
virtual ~node_key() {}
protected:
Key _key;
};
Now I have two types of child nodes one which inherits from node_key and one which only inherits from node_base
struct no_key {};
template<typename Key, typename Data>
struct child: public node_key<Key> {
…
void foo() {
//do something with _data
}
protected:
Data _data;
}
template<typename Data>
struct child<no_key,Data>: public node_base {
…
void foo() {
//do something with _data
}
protected:
Data _data;
}
However at you see I write foo twice and it is identical in both cases. Can I do something to ensure reuse? The advantage of node_key is that I can have a pointer
node_key<int> *p=new child<int,int>
…
p->foo();
and it will fail at compile time if p=new child< int > which is fine. I can also have a pointer.
node_base *p=get_a_child();
p->foo();
More about my tree here: https://www.facebook.com/profile.php?id=100013861179843
Aucun commentaire:
Enregistrer un commentaire