在编译时将类型转换为整数

Convert a type to an integer at compile-time?

本文关键字:整数 类型转换 编译      更新时间:2023-10-16

在C 中是否有办法将类型转换为Compile-time(也许使用TypeID)的整数?我的目标是通过该类中的每种类型传递唯一代码:

template<int TypeCode>
class MyClass
{
};

编辑:有关我要做的事情的更多详细信息。实际上,myclass会更像:

template<int Code>
class AbstractBase
{
};

我用大量的CRTP技术编写了一个高度的模板代码,我需要检查某些操作之间的兼容性代码。为此,我的想法是从抽象库类中继承兼容类型,为所有这些类型指定相同的代码。使用此操作,只需调用std::enable_if<std::is_base_of<AbstractBase<MyCode>, T>::value>::type,我就可以检查某些操作的类型兼容性。

一阶,我可以手工生成一个代码,但是如果我可以自动从类型生成此代码,它将更加优雅。

有很多方法。这是模板专业化:

#include<iostream>
using namespace std;
template<class T>   struct type_code        { enum{value=0}; };  // unknown type code
template<>          struct type_code <int>  { enum{value=1}; }; 
template<>          struct type_code <float>{ enum{value=2}; }; 
int main() {
        cout << type_code<void>::value << endl;
        cout << type_code<int>::value << endl;
        cout << type_code<float>::value << endl;
}

输出:

0
1
2

不确定我是否完全了解您。这是你在说什么吗?

template<int TypeCode>
class MyClass
{
private:
    int i;
    double d;
public:
    template<typename T>
    operator T()
    {
        if(strcmp(typeid(T).name(),"int")==0)
            return i;
        else if(strcmp(typeid(T).name(),"double")==0)
            return d;
        // some other types here ...
    }
};

好吧,您可以创建一个类型列表,然后在编译时提取该列表中的类型索引。

从我的另一个答案中,这是这种技术:

#include <type_traits>
template<typename... Types>
struct Seq {};
template<typename T, typename Seq, typename=void>
struct IndexOf;
template<typename T, typename First, typename... Types>
struct IndexOf<T, Seq<First, Types...>, typename std::enable_if< std::is_same<T, First>::value >::type > {
  enum { value = 0 };
};
template<typename T, typename First, typename... Types>
struct IndexOf<T, Seq<First, Types...>, typename std::enable_if< !std::is_same<T, First>::value >::type > {
  enum { value = 1+IndexOf<T,Seq<Types...>>::value };
};
typedef Seq< bool, char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long > IntegerTypes;
#include <iostream>
int main() {
  std::cout << IndexOf< int, IntegerTypes >::value << "n";
  // this next line will not compile, because void is not in the IntegerTypes sequence:
  // std::cout << IndexOf< void, IntegerTypes >::value << "n";
}

我在整数上使用它。

因此,如果您有要整数的类型列表,则可以列出所有类型,上述技术将为每个类型提供一个独特的整数(反向映射也相对容易 - 编译时间索引到列表类型)。