Reputation: 323
I have implemented a red black tree and it works fine. However, I need to make this in such a way that it can be used with any data type by using templates( generics) in C++. When adding items to the tree , both the key and the item itself should be generic types (C++ Templates)
Code:
RB_Node* RedBTree::RBTInsert(void* key, void* item)
{
RB_Node* y;
RB_Node* x;
RB_Node* newNode;
//rest of algorithm
}
How do you do those 2 arguments as generic? I am new to C++ and templates themselves, any help is really appreciated
Upvotes: 1
Views: 462
Reputation: 154005
You would start your declarations with template
, followed by a suitable set of template parameters, replace you void*
by the resulting name, and pretend that the template parameters just happen to be normal types. As long as you don't need any associated types and your code only needs to work for regular type arguments, you'll be fine:
template <typename Key, typename Value>
RB_Node* RedBTree<Key, Value>::RBInsert(Key const& key, Value const& item)
{
// pretty much like before...
}
When I started working with template I first implemented my code with concrete types, made sure it worked, and then replaced the concrete types with template parameters. After some time (I think a bit less than 5 years) I skipped writing things with concrete types first. It turns out that once you know about the template stuff, writing in terms of concepts is actually easier than bothering with concrete types.
Upvotes: 2