c++ - 编译时模板 `std::integral_constant` 计数器 - 如何实现它?

标签 c++ templates c++11 c++14 constexpr

我有几种类型,我想“绑定(bind)”一个 std::integral_constant编译时每种类型的顺序 ID 值。

例子:

struct Type00 { };
struct Type01 { };
struct Type02 { };
struct Type03 { };
struct TypeXX { };
struct TypeYY { };

template<typename T> struct TypeInfo
{
    using Id = std::integral_constant<int, ???>;
};

int main()
{
     cout << TypeInfo<Type00>::Id::value; // Should always print 0
     cout << TypeInfo<Type01>::Id::value; // Should always print 1
     cout << TypeInfo<Type02>::Id::value; // Should always print 2
     cout << TypeInfo<Type03>::Id::value; // Should always print 3
     cout << TypeInfo<TypeXX>::Id::value; // Should always print 4
     cout << TypeInfo<TypeYY>::Id::value; // Should always print 5
}

问题是我不知道如何跟踪上次使用的 ID。理想情况下,我想要这样的东西:

template<typename T> struct TypeInfo
{
    using Id = std::integral_constant<int, lastUsedID + 1>;
};

有什么方法可以定义和跟踪编译时 lastUsedID ?

我该如何解决这个问题?


编辑:

说明:

  • TypeInfo<...>需要在用户代码中频繁调用。语法必须保持清晰(用户不需要(需要知道有一个)/(手动增加)编译时计数器)
  • Typeinfo<T>::Id::value在整个程序中必须始终返回相同的值。初始值将在第一次实例化时“绑定(bind)”到 lastUsedID + 1 .
  • 我可以使用所有 C++11 和 C++14 功能。
  • 在调用 TypeInfo<...> 之前列出所有类型不是一个合适的解决方案。

最佳答案

这是不可能的,而且很容易看出原因:考虑两个编译单元。第一单元看到类型 Type00,但不是 Type01,而第二单元看到 Type01 而不是 Type00。 C++(包括 C++11 和 C++14)中没有任何内容可以告诉编译器在两个编译单元中这些类型应该具有的顺序。即使在链接时向目标文件添加一些数据也为时已晚,因为您要求的是编译时值。这是编译单元的基本概念,它为您所要求的功能设置了一个硬性障碍。

关于c++ - 编译时模板 `std::integral_constant` 计数器 - 如何实现它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25916933/

相关文章:

c++ - 使用 PoDoFo 库从 PDF 运算符中的数组 TJ 中提取文本

c++ - Qt 终止由 QConcurrent::run 生成的线程

c++ - Friend 模板函数(在非模板类中),C++

c++ - 如何编写一个不断敲击输出的包装器?

c++ - 我该如何解决这个错误? CRT 检测到应用程序在堆缓冲区结束后写入内存

c++ - 随机 double 总是无限的

c++ - 函数指针在C和C++中都立即返回吗?

c++ - boost async_read 与阻塞同步线程 - 性能差异?

c++ - 有没有办法获取容器模板类型以将其与另一个 value_type 重用?

c++ - 指向不同返回类型和签名的函数的指针映射