2012-12-19 22 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"; 
} 

我使用它的整數位置。所以如果你有一個你想要的整數類型的列表,你可以列出所有的類型,而上面的技術會給每一個整數(反向映射也相對容易 - 編譯時間索引進入列表中鍵入)。

相關問題