dimanche 26 février 2017

Using function pointers to uniquely identify types

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.

Aucun commentaire:

Enregistrer un commentaire