我想下面的代碼重載一個簡單的函數來爲多種類型工作。但是,它不能編譯。有人可以告訴我什麼是錯的,以及如何解決這個問題?模板代碼returntype重載不編譯。什麼是錯的
typedef struct str1_type
{
int f1;
int f2;
} STR1;
typedef struct str2_type
{
char f1[100];
char f2[100];
}STR2;
template <typename T1, typename T2>
T2 getFieldOffset(const T1& t, int i);
int main() {
STR1 str1;
STR2 str2;
int i = getFieldOffset(str1,0);
const char* test = getFieldOffset(str2,0);
}
template <typename T1, typename T2>
T2 getFieldOffset(const T1& t, int i)
{
switch (i) {
case 0:
return t.f1;
case 1:
return t.f2;
default:
{
cout << "Invalid index passed: i" << i << endl;
return null;
}
}
}
以下是錯誤消息:
test2.cpp: In function 'int main()':
test2.cpp:73: error: no matching function for call to 'getFieldOffset(STR1&, int)'
test2.cpp:75: error: no matching function for call to 'getFieldOffset(STR2&, int)'test2.cpp: In function 'T2 getFieldOffset(const T1&, int)':
test2.cpp:90: error: 'null' was not declared in this scope
那麼,你收到什麼錯誤信息? – yan 2011-04-11 15:51:32
剛更新錯誤消息。對不起,以前錯過它 – Kiran 2011-04-11 15:54:11