I need to get a unique ID which I could use as a template argument (which means it must be statically determined at compile-time), for each member function of my class. My first idea was to use the index of the function within the class, but as far as I can tell, there's no way to obtain it. So, I'm trying to use the offset of the member function within the class, but I cannot figure out how to obtain it:
#include <iostream>
#include <typeinfo>
class MyClass {
template <typename F>
size_t getUniqueId(F f) {
return ...something unique, maybe based on f's offset?...
}
public:
void method1(bool) {
std::cout << "My ID is " << getUniqueId(&MyClass::method1) << '\n';
}
void method2(int) {
std::cout << "My ID is " << getUniqueId(&MyClass::method2) << '\n';
}
void method3(bool) {
std::cout << "My ID is " << getUniqueId(&MyClass::method3) << '\n';
}
};
int main()
{
MyClass a;
a.method1(true);
a.method2(1);
a.method3(true);
}
I tried implementing getUniqueId() like this:
template <typename F>
size_t getUniqueId(F f) {
return typeid(f).hash_code();
}
but (unsurprisinlgy) this doesn't work, because it returns the same value for method1 and method3, since their signature is the same.
I think I will have to resort to using preprocessor macros (I could just use the __LINE__ one to get a unique ID from within the method), but a clean C++ solution would be preferable.