我有以下代碼(從實際項目精簡版重現 問題)導致一個編譯器錯誤在RHEL5(G 4.1.2 ++版):G ++ 4.1.2編譯器錯誤
----------- driver (test.cpp)--------------
#include <iostream>
#include <classa.hpp>
#include <func.hpp>
namespace globals {
static int kth(const A& a) {
return kth(a.ival());
}
}
using namespace globals;
int main() {
A a;
std::cout << func(a) << std::endl;
return 0;
}
----------class A (classa.hpp)------------
class A {
public:
A():val(0){}
const int ival() const {return val;}
private:
int val;
};
------- namespace globals (func.hpp) ------
namespace globals {
int kth(const int& c) {
return c;
}
template <class T>
int func(const T& key) {
return kth(key);
}
}
--------------------------------------------
採用G ++ 4.1.2編譯它給了我下面的錯誤:
func.hpp: In function ‘int globals::func(const T&) [with T = A]’:
test.cpp:15: instantiated from here
func.hpp:8: error: invalid initialization of reference of type ‘const int&’ from
expression of type ‘const A’
func.hpp:2: error: in passing argument 1 of ‘int globals::kth(const int&)’
相同的代碼編譯和運行完全正常的RHEL4(G ++版本3.4.6)!有關如何解決RHEL5上的此錯誤(?)的任何解釋/想法/建議,請致電 !
編輯: 謝謝謝爾蓋。這是我已經知道的明顯解決方案。但我忘了補充說,限制是func.hpp不能被編輯(例如,它的第三方被寫保護)。任何解決方法?
請正確格式化您的代碼 – Robert 2010-12-17 04:03:05
解決方法如果您無法編輯func.hpp:在#include-func之前放置一個'kth(const A&)'或一個#include的聲明,它將在test.cpp中得到這樣的聲明。 HPP。但是它是不好的形式,func.hpp使用'kth'而沒有看到所有重載的聲明。 – aschepler 2010-12-17 18:15:14
@aschelper:謝謝你,會測試一下。 @aschelper上的 – 2010-12-18 03:24:46