0

奇妙なリンクエラーが発生しています。この種の問題を回避するために、ここに示す手順に従いましたが、ヘッダーと実装ファイルを分割する方法がわかりません。

これが私のテストファイルです:

#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

私は何が間違っているのですか?私を助けてください!

4

1 に答える 1

2

(メンバー)関数テンプレートは関数ではありません。それらをインスタンス化しない限り、リンカはそれらを認識しません。ソースファイルは個別にコンパイルされるため、(メンバー)関数テンプレートを1つのソースファイルに入れて明示的にインスタンス化しない場合、リンカはそれを認識しません。

したがって、あなたの場合、関数テンプレートはで関数に変換されていないcargo.oため、リンカはmain.oそれに依存しているため、エラーを報告します。テンプレートをヘッダーファイルに入れるか、で明示的にインスタンス化する必要がありますcargo.cpp

于 2010-11-04T12:17:14.297 に答える