1

If I write a trait like this,

template <typename T>
struct is_int {
  static constexpr bool value = false;
};

template <>
struct is_int<int> {
  static constexpr bool value = true;
};

Is the value actually stored in memory when the program runs? For example, if I use this trait on a million different types, does the program use 1 MB of memory to store these values?

To paraphrase, is there still any advantage to using

template <typename T>
struct is_int {
  enum { value = 0; }
};

template <>
struct is_int<int> {
  enum { value = 1; }
};
ildjarn
  • 62,044
  • 9
  • 127
  • 211
SU3
  • 5,064
  • 3
  • 35
  • 66

1 Answers1

1

At a minimum, a compiler will map multiple equal constants onto each other, so all the classes/instances would share a single byte (or four byte, or whatever).

Depending on the usage of a constants's value (in the code it is referred to), the compiler might remove it completely as 'unnecessary intermediate', because it can derive the outcomes of the IF's or wherever it is used directly (statically).

Aganju
  • 6,295
  • 1
  • 12
  • 23