2010-11-04 100 views
0

我有一個奇怪的鏈接錯誤。我遵循here提供的說明來避免這種問題,但我無法弄清楚如何拆分頭文件和實現文件。鏈接錯誤:模板化的朋友操作員超載

這是我的測試文件:

#include <cargo.h> 
#include <iostream> 
#include <string> 

using namespace std; 
using namespace dom; 

int main() 
{ 
    dom::cargo<string> text("Hello, World!"); 

    cout << text << endl; 

    return 0; 
} 

頭文件class cargo包含在測試:

#ifndef CARGO_H 
#define CARGO_H 1 

#include "node.h" 

#include <iostream> 

namespace dom 
{ 
    template <typename Type> class cargo; 

    template <typename Type> 
    std::ostream& operator<<(std::ostream&, const dom::cargo<Type>&); 

    template <typename Type> 
    class cargo 
     : public dom::node 
    { 
     Type value; 

    public: 
     cargo() 
      : value() 
     { } 

     cargo(Type value) 
      : value(value) 
     { } 

     friend std::ostream& operator<< <>(std::ostream&, const dom::cargo<Type>&); 
    }; 
} 

#endif // !CARGO_H 

及其實施:

#include "cargo.h" 

template <typename Type> 
std::ostream& operator<< (std::ostream& ostream, dom::cargo<Type>& cargo) 
{ 
    return (ostream << cargo.value); 
} 

我使用的CMake編譯並將其全部鏈接起來。 的鏈接錯誤我得到的是有關未定義參考operator <<

Scanning dependencies of target test 
[100%] Building CXX object Tests/CMakeFiles/test.dir/test0.c++.o 
Linking CXX executable test 
CMakeFiles/test.dir/test0.c++.o: In function `main': 
test0.c++:(.text+0x9b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& dom::operator<< <std::basic_string<char, std::char_traits<char>, std::allocator<char> > >(std::basic_ostream<char, std::char_traits<char> >&, dom::cargo<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > const&)' 
collect2: ld returned 1 exit status 
make[2]: *** [Tests/test] Error 1 
make[1]: *** [Tests/CMakeFiles/test.dir/all] Error 2 
make: *** [all] Error 2 

我在做什麼錯?請幫幫我!

回答

2

(成員)函數模板不是函數;鏈接器不會看到它們,除非你實例化它們。源文件是分開編譯的,所以如果你把一個(成員)函數模板放在一個源文件中,並且沒有明確地實例化它,鏈接器就不會看到它。

所以在你的情況下,函數模板還沒有變成cargo.o中的函數,所以鏈接器報告錯誤,因爲main.o依賴於它。您需要將模板放在頭文件中,或者在cargo.cpp中明確實例化它。

+0

瞭解!謝謝! :) – Rizo 2010-11-04 12:29:29