C++ 自动生成唯一的类型ID,反之亦然
,是否也可以将C++ 自动生成唯一的类型ID,反之亦然,c++,templates,c++11,template-meta-programming,C++,Templates,C++11,Template Meta Programming,,是否也可以将大小\u t分配给类型?i、 e: template <size_t N> struct IntToType { typedef ??? type; // ??? }; TypeID::value<int>(); // "assigns" 0 to int IDType<0>::type; // resolves to int TypeID::value<IDTyp
大小\u t
分配给类型?i、 e:
template <size_t N>
struct IntToType {
typedef ??? type; // ???
};
TypeID::value<int>(); // "assigns" 0 to int
IDType<0>::type; // resolves to int
TypeID::value<IDType<0>::type>(); // resolves to 0
模板
结构IntToType{
类型定义???类型;/???
};
TypeID::value();//将“0”赋值给int
IDType::type;//解析为int
TypeID::value();//解析为0
我认为语言设计是不可能的,这种递归可能是不可能的,因为它可能取决于代码的编译顺序,但我还是要问
如果另一种方法可行的话,可以使用任何其他方法为每种类型定义唯一的ID。我无论如何都不是模板专家,所以我不知道这方面有什么漏洞,但似乎您可以使用模板专门化硬连接类型信息,如下所示:
template <typename T>
struct TypeId {
};
template <>
struct TypeId<int> {
static const size_t value = 0;
};
template <>
struct TypeId<unsigned> {
static const size_t value = 1;
};
template <>
struct TypeId<long> {
static const size_t value = 2;
};
template <>
struct TypeId<unsigned long> {
static const size_t value = 3;
};
template <>
struct TypeId<float> {
static const size_t value = 4;
};
template <>
struct TypeId<double> {
static const size_t value = 5;
};
// ------
template <size_t N>
struct TypeInfo {
};
template <>
struct TypeInfo<TypeId<int>::value> {
typedef int type;
static constexpr char const* name = "int";
};
template <>
struct TypeInfo<TypeId<unsigned>::value> {
typedef unsigned type;
static constexpr char const* name = "unsigned int";
};
template <>
struct TypeInfo<TypeId<long>::value> {
typedef long type;
static constexpr char const* name = "long int";
};
template <>
struct TypeInfo<TypeId<unsigned long>::value> {
typedef unsigned long type;
static constexpr char const* name = "unsigned long int";
};
template <>
struct TypeInfo<TypeId<float>::value> {
typedef float type;
static constexpr char const* name = "float";
};
template <>
struct TypeInfo<TypeId<double>::value> {
typedef double type;
static constexpr char const* name = "double";
};
// ---
void func(int i)
{
std::cout << "func int\n";
std::cout << TypeInfo<TypeId<decltype(i)>::value>::name << '\n';
}
void func(float f)
{
std::cout << "func float\n";
std::cout << TypeInfo<TypeId<decltype(f)>::value>::name << '\n';
}
int main()
{
TypeInfo<0>::type n1 = {};
TypeInfo<4>::type n2 = {};
func(n1);
func(n2);
std::cout << TypeInfo<TypeId<int>::value>::name << ": " << TypeId<int>::value << '\n';
std::cout << TypeInfo<TypeId<unsigned>::value>::name << ": " << TypeId<unsigned>::value << '\n';
std::cout << TypeInfo<TypeId<double>::value>::name << ": " << TypeId<double>::value << '\n';
}
即使有办法做到这一点,我怀疑Filip Ros的“有状态元编程”技术也许能完成这样的事情——委员会正在计划禁止它,所以没有太多的要点。你考虑过使用<代码> STD::Type指数> <代码>吗?(但老实说,我不知道你的问题是什么。)@T.C.的答案是,我会接受的。所以好吧,也许有可能,但是会被禁止。好吧,我是想自动完成的。在代码评审时,大小分配是由编译器自动完成的,但不是硬连接的。@alesegdia啊,好吧,反正我玩得很开心。;)
func int
int
func float
float
int: 0
unsigned int: 1
double: 5