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

Vit*_*meo 6 c++ templates constexpr c++11 c++14

我有几种类型,我想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
}
Run Code Online (Sandbox Code Playgroud)

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

template<typename T> struct TypeInfo
{
    using Id = std::integral_constant<int, lastUsedID + 1>;
};
Run Code Online (Sandbox Code Playgroud)

有没有办法定义和跟踪编译时间lastUsedID

我怎么解决这个问题?


编辑:

澄清:

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

Dan*_*rey 3

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