代码之家  ›  专栏  ›  技术社区  ›  Rizo

链接错误:模板化友元运算符重载

  •  0
  • Rizo  · 技术社区  · 15 年前

    我有一个奇怪的链接错误。我按照说明做了 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
    

    我做错什么了?请帮帮我!

    1 回复  |  直到 15 年前
        1
  •  2
  •   Oliver Charlesworth    15 年前

    (成员)函数模板不是函数;除非实例化,否则链接器看不到它们。源文件是单独编译的,因此如果您将(成员)函数模板放在一个源文件中而不显式实例化它,链接器将看不到它。

    因此,在您的示例中,函数模板尚未转换为 cargo.o ,因此链接器报告错误,因为 main.o 取决于它。您需要将模板放在头文件中,或者显式实例化它 cargo.cpp .

    推荐文章