【发布时间】:2014-09-18 15:36:31
【问题描述】:
我有几种类型,我想在编译时将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必须始终在整个程序中返回相同的值。初始值将在第一次实例化时“绑定”到lastUsedID + 1。 - 我可以使用所有 C++11 和 C++14 功能。
- 在调用
TypeInfo<...>之前列出所有类型不是一个合适的解决方案。
【问题讨论】:
-
您可以在下一个继承每个连续的并递增。什么的。
-
编译单元(不同的源文件)之间如何,需要值一致吗?不重叠?你愿意在某处列出所有类型的清单吗?它们必须是连续的还是唯一的?知道你可以采取的确切位置比所有人都少,可以让你的问题更容易解决。
-
你可能对this answer感兴趣。
-
如果可以在不同的头文件中定义类型,那么我很确定标准 C++ 中没有办法拥有连续的编译时常量类型 ID,这些 ID 保证在整个程序,而不提供明确的类型列表。这是因为程序的不同部分是分开编译的。如果
a.cpp包含TypeInfo<A>; TypeInfo<B>;并且b.cpp包含TypeInfo<B>; TypeInfo<A>;,那么读取时反增量方法将产生不同的ID。你需要放弃一个你的要求。
标签: c++ templates c++11 c++14 constexpr