lundi 4 février 2019

Is there a way to create unique type Id at compile time in C++

I can create a unique type id the following way:

template<typename T>
struct TypeId
{
  static size_t value()
  {
    return reinterpret_cast<size_t>(&TypeId<T>::value);
  }
};


auto intType = TypeId<int>::value();

It works at runtime but is there a way to do it at compile time ? I would like to use it in a switch statement like this:

switch (typeId)
{
  case TypeId<int>::value():
    // do something
    break;

  case TypeId<double>::value():
    // do something
    break;

  case TypeId<MyClass>::value():
    // do something
    break;
}

The problem here is that I cannot convert a pointer to the size_t at compile time:

template<typename T>
struct TypeId
{
  static constexpr size_t value()
  {
    return reinterpret_cast<size_t>(&TypeId<T>::value);
  }
};

constexpr auto id = TypeId<int>::value();

The example above gives the following error:

error: conversion from pointer type ‘size_t (*)() {aka long unsigned int (*)()}’ to arithmetic type ‘size_t {aka long unsigned int}’ in a constant expression
   constexpr auto id = TypeId<int>::value();

Aucun commentaire:

Enregistrer un commentaire