user4602510
user4602510

Reputation:

Using function as class member in C++

I have came from Java, I have some knowledge of C++ and C, but not deep. I am creating hashtable class, it will encapsulate storing values and keys. But the question is what is a better approach to pass, for example, in constructor custom function which will calculate a hash key in the table.

In java I would use function (interface) setting it as class member. What is the best practice to do this in C++, use the function pointer as member? Please suggest how to implement this.

Upvotes: 0

Views: 165

Answers (1)

Adam Sosnowski
Adam Sosnowski

Reputation: 1284

The C++ practice is to parametrize your class with callable type that will calculate the hash:

template<class Key, class Value, class Hash> class hashtable;

This allows to have any callable object as your hash function, be it plain function or functor object.

Then pass callable object in the constructor:

template<class Key, class Value, class Hash>
class hashtable
{
  hashtable(Hash h);
};

This allows you to specify different hash functions without creating new classes.

Finally, to make declaration and construction of hashtables more convenient, we specify default template parameters and constructor arguments:

template<class Key, class Value, class Hash = std::hash<Key> >
class hashtable
{
  hashtable(Hash h = Hash());
};

Upvotes: 1

Related Questions