2013-05-16 57 views
2
#include <iostream> 
#include <typeinfo> 
#include <map> 
#include <stdlib.h> 
using namespace std; 

struct foo { 
    int one; 
    int i; 
    int s; 
}; 

template<class myType> 
void serialize(myType b, string &a, int epe) { 

    //three.resize(42); 
    int type = typeid(b).name()[35] == 'S' ? 1 : 0; // testing if the map(b) value weather a struct        or an int 

    if (type) { 
     auto it = b.begin(); 
     cout << sizeof(it->second)/sizeof(int) << endl; 
     cout << it->second.one; 
    } else { 
     cout << sizeof(b)/sizeof(int) << endl; 
    } 

} 

int main() { 
    cout << "Hello world!" << endl; 
    map<int, int> hey; 

    map<int, foo> heya { 
     { 1, { 66 } }, 
    }; 

    typedef map<int, foo> mappy; 
    typedef map<int, int> happy; 

    string duck; 
    auto it = heya.begin(); 
    serialize<happy>(hey, duck, 4); 
    serialize<mappy>(heya, duck, 4); 

    return 0; 
} 

所以我得到這個錯誤,我認爲它是因爲它的地圖 與int類型(map<int,int>)的值在模板 功能的一部分,測試其不應該達到它的一個int而不是一個結構體,儘管我在使用該函數之前嘗試了專門化該類型,仍然無法工作。傳遞多個(不同)類型的參數模板函數

serialize\main.cpp|36|error: request for member 'one' in  'it.std::_Rb_tree_iterator<_Tp>::operator-> 
    [with _Tp = std::pair<const int, int>, std::_Rb_tree_iterator<_Tp>::pointer = std::pair<const int, int>*]()->std::pair<const int, int>::second', 
    which is of non-class type 'int'| 
    ||=== Build finished: 1 errors, 1 warnings ===| 
+0

'second'的類型爲'int',所以它沒有叫'one'的成員。如果要爲特定類型提供支持,則需要提供超載。 –

+0

無論如何,'typeid'是一個不好的方法,因爲'name()'的結果是實現定義的。對於元編程,使用'std :: is_same'。 – chris

回答

0

if僅在運行時評估。

在編譯時,編譯器不知道編譯時if將是true還是false。所以一般來說,所有的代碼必須是可編譯的,而不管它是否處於條件之內。

您需要使用重載函數。

typedef map<int, foo> mappy; 
typedef map<int, int> happy; 

template<class myType> 
void serialize(myType b, string &a, int epe) { 
    cout << sizeof(b)/sizeof(int) << endl; 
} 

void serialize(mappy b, string &a, int epe) { 
    auto it = b.begin(); 
    cout << sizeof(it->second)/sizeof(int) << endl; 
    cout << it->second.one; 
} 

serialize<happy>(hey, duck, 4); 
serialize(heya, duck, 4); 
+1

啊!打敗了我。這就是我得到奶昔的原因。 –

+0

嗯,謝謝,但沒有任何機會以另一種方式做到這一點,而不使用重載函數? – user2390934

相關問題