static constexpr member storage

时间:2016-07-30 15:07:24

标签: c++ templates c++11 c++14

如果我写这样的特质,

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

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

程序运行时value是否实际存储在内存中?例如,如果我在一百万种不同类型上使用此特征,程序是否使用1 MB内存来存储这些值?

换句话说,使用

还是有什么好处的
template <typename T>
struct is_int {
  enum { value = 0; }
};

template <>
struct is_int<int> {
  enum { value = 1; }
};

1 个答案:

答案 0 :(得分:1)

编译器至少会将多个相等的常量映射到彼此,因此所有类/实例将共享一个字节(或四个字节,或其他)。

根据常量值的使用(在引用的代码中),编译器可能会将其完全删除为“不必要的中间”,因为它可以导出IF或其他任何地方的结果它直接使用(静态)。

相关问题