简体   繁体   中英

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.

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 hashtable s 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());
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM