0

次のコードは、Visual Studio 2015 では問題なくコンパイルされますが、minGW ではその下に示す警告とエラーが発生します。

#include <iostream>
using std::ostream;

template<typename ElemType, int SIZE>
class Array
{
    friend ostream &operator<<(ostream &out, const Array<ElemType, SIZE> &value);

    ElemType operator[](int index) const;

private:
    ElemType elements[SIZE];
};

template<typename ElemType, int SIZE>
ostream &operator<<(ostream &out, const Array<ElemType, SIZE> &value);

template<typename ElemType, int SIZE>
ostream &operator<<(ostream &out, const Array<ElemType, SIZE> &value)
{
    out << elements[0];
    return out;
}

mingw32-g++.exe -Wall -g -pedantic-errors -pedantic -Wextra -Wall -std=c++98 -c Test.cpp
Test.cpp:7:79: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Array<ElemType, SIZE>&)' declares a non-template function [-Wnon-template-friend]
Test.cpp:7:79: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) 
Test.cpp: In function 'std::ostream& operator<<(std::ostream&, const Array<ElemType, SIZE>&)':
Test.cpp:21:11: error: 'elements' was not declared in this scope

私はこのようなもののいくつかについて専門家とはほど遠いので、問題が何であるかはわかりません. クラス自体のフレンド宣言の直前に次のコードが必要だと言っているようですが、そこに置くと他のコンパイルエラーが発生します:

template<typename ElemType, int SIZE>

前もって感謝します!

以下の投稿で @Trevor Hickey によって提案された変更を行った後、フレンド テンプレート機能に関する警告は消えました。ただし、「要素」(フレンド関数内) がスコープ内で宣言されていないというエラーが引き続き発生します。

4

2 に答える 2