1

在 C++ 中,有没有办法在编译时将类型转换为整数(可能使用 typeid)?我的目标是为该类中的每种类型传递一个唯一代码:

template<int TypeCode>
class MyClass
{
};

编辑:有关我正在尝试做的事情的更多详细信息。事实上,MyClass 会更像这样:

template<int Code>
class AbstractBase
{
};

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

首先,我可以手动生成代码,但如果我可以从类型自动生成此代码,它会更优雅。

4

3 回答 3

2

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

#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
于 2012-12-19T19:59:03.357 回答
0

不确定我是否完全理解你。这就是你在说的吗?

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 ...
    }
};
于 2012-12-19T20:04:07.257 回答
0

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

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

#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";
}

我在整数上使用它。

所以如果你有一个你想要整数的类型列表,你可以列出所有类型,上面的技术将为每个类型提供一个唯一的整数(反向映射也相对容易——编译时索引到列表中类型)。

于 2012-12-19T20:35:08.247 回答