#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 ===|
'second'的類型爲'int',所以它沒有叫'one'的成員。如果要爲特定類型提供支持,則需要提供超載。 –
無論如何,'typeid'是一個不好的方法,因爲'name()'的結果是實現定義的。對於元編程,使用'std :: is_same'。 – chris