1

I need to assign unique values to types for run-time equality comparison. Using function pointers as values does the job:

#include <cassert>

struct type_id {
  using value_type = void(*)();

  template<class T>
  static void get() { }
};

// some types
struct A {};
struct B {};

int main() {
    type_id::value_type a = &type_id::get<A>;
    type_id::value_type b = &type_id::get<B>;   

    assert(a != b);

    return 0;
}

My question is the following: what are the restriction (if any) I should be aware of? I am especially curious about uniqueness across multiple translation units, and performance.

max
  • 1,048
  • 10
  • 20
  • 1
    Hi Max, I guess you have to check COMDAT-folding and weak linking (and how to avoid it) – JVApen Feb 26 '17 at 18:54
  • If you know in advance what are your types, you can assign unique _types_ at compile-time. This would wipe out your doubts about performance... – skypjack Feb 26 '17 at 19:26
  • @JVApen thanks, that's *exactly* the kind of references I was looking for. The standard [apparently](http://stackoverflow.com/questions/26533740/do-distinct-functions-have-distinct-addresses#comment41694674_26533963) enforces that function pointers will compare different for each instantiation. In order to avoid COMDAT folding I might be safer by putting some local static variable inside my functions and returning their address so that function bodies are different. – max Feb 26 '17 at 20:27
  • 1
    I used a similar technique a bunch of times and it *usually* works. I highly recommend going down the static variable address inside the function route though as I remember having situations where the addresses were not the same across translation units with GCC when only using function pointers. I ended up just using `void*` as my type identifiers. – moka Feb 26 '17 at 21:16
  • Thanks for the feedback. I had the local static variable approach in mind initially until I realized using function pointers directly would be more efficient, but I suspected there could be issues... On a quick test with two TU, it seems both clang and gcc-6 give the expected result though. – max Feb 26 '17 at 21:44

0 Answers0