2012-12-19 24 views
1

在C++中是否有一种方法可以在编译时将类型转换为整数(可能带有typeid)? 我的目标是通过一个独特的代码,在类中的每个类型:在编译时将类型转换为整数?

template<int TypeCode> 
class MyClass 
{ 
}; 

编辑:什么我试图做一些更多的细节。 事实上,MyClass的会更喜欢的是:

template<int Code> 
class AbstractBase 
{ 
}; 

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

在一阶,我可以手动生成代码,但它会更优雅,如果我可以自动生成类型的代码。

+1

'static_cast'如果它可以正确转换。 'typeid'是运行时。 – chris

+0

这是不可能的,从一种得到一个编译时整,但你可以从绑定到一个类型,然后可转换成整数的地址获取运行时整... –

+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 
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 ... 
    } 
}; 
+0

这不是编译时 –

+0

@Leonid - 它不是,但他在他的问题,这是RTTI提到的typeid。 – StackHeapCollision

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

我使用它的整数位置。所以如果你有一个你想要的整数类型的列表,你可以列出所有的类型,而上面的技术会给每一个整数(反向映射也相对容易 - 编译时间索引进入列表中键入)。

相关问题