So I’m implementing a boost::hash_value override for my class that is exported from a shared library. I’d like to have that hash_value function available for everyone who uses this class. Currently my hash_value function is exported and defined in the cpp file, even though it just calls an inline member of my class. Instead, I’d like this hash_value function to also be inlined as to avoid unneeded function calls. Currently the header’s like this:
#ifdef MYDLL
#define MY_API __export
#else
#define MY_API __import
#endif
class MY_API MyGUID
{
public:
...
inline size_t Hash() const
{ return m1 ^ m2; }
...
private:
size_t m1,m2;
};
namespace boost
{
// Defined in .cpp file; just returns inGUID.Hash();
MY_API size_t hash_value(const MyGUID &inGUID);
}
But I’d like that hash_value to be more like:
namespace boost
{
// I'd like to inline this, like so:
static inline size_t hash_value(const MyGUID &inGUID)
{
return inGUID.Hash();
}
}
Except this code above defines hash_value in every .cpp file that includes it, quite likely littering the binary, and is ugly in principle.
Putting aside the question of whether the function calls make a measurable difference in performance, how can I get my class’ Hash function inlined for clients of this shared library that use MyGUID in hashed containers like ordered_set?
I suspect it involves templates, but I couldn’t quite figure out how.
If you look inside
boost/functional/hash/hash.hppyou will see that hash_value for existing types are defined like:If boost already uses technique this is your hint that it is safe for you to do the same! Regarding your concern about inefficiencies of using
inlinein the header file, that is precisely how it is designed to be used and since your function is simply forwarding to another function call it will probably lead to no increase in code size at all.Unless you are going to be doing something very fancy with preprocessor directives it does not make much sense to use
static inline, i.e., if you just need one version of this function just mark it asinline.