2010-12-17 133 views
1

我有以下代碼(從實際項目精簡版重現 問題)導致一個編譯器錯誤在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不能被編輯(例如,它的第三方被寫保護)。任何解決方法?

+1

請正確格式化您的代碼 – Robert 2010-12-17 04:03:05

+0

解決方法如果您無法編輯func.hpp:在#include-func之前放置一個'kth(const A&)'或一個#include的聲明,它將在test.cpp中得到這樣的聲明。 HPP。但是它是不好的形式,func.hpp使用'kth'而沒有看到所有重載的聲明。 – aschepler 2010-12-17 18:15:14

+0

@aschelper:謝謝你,會測試一下。 @aschelper上的 – 2010-12-18 03:24:46

回答

2

這是發生了什麼。當定義函數func()時,編譯器不知道函數kth(const A&),但因爲它在代碼後面定義。因此,當它在func()內遇到對kth()的引用時,它會假定它是對kth(const int&)的引用。現在,當func()實際被實例化時,它不能編譯它,因爲T是A,而不是int。我不確定爲什麼它可以在另一個版本的編譯器中工作,但我認爲這是因爲它實際上是在實例化模板函數時開始解析引用,而不是在聲明時纔開始解析引用。但是這看起來像舊版本中的一個錯誤,因爲有了這樣的行爲,函數定義會根據從何處實例化而改變,這非常令人困惑。

只有這樣,才能解決您的代碼,它與任何編譯器的工作原理是把的kth(const A&)定義kth(const int&)和FUNC()或kth(const A&)以上FUNC某處向前聲明()之間。

更新

有了不編輯func.hpp我能想到的最好的解決方法的限制是爲了創建一個自定義的頭文件像這樣的東西:

#include <classa.hpp> 
namespace globals { 
    static int kth(const A& a); // defined later, but used by func.hpp 
} 
#include <func.hpp> 

我也不要」 t瞭解爲什麼kth(const A&)被定義爲靜態,但是由全局標題使用。我寧願將它放入classa.cpp中,並將其聲明放入classa.hpp中。但這可能是一些我不知道的設計特性或工件。

+0

謝謝謝爾蓋。用我的編輯(約束),@ aschelper的修復解決了錯誤。 – 2010-12-18 04:30:24