0

私のテンプレートクラスは次のようになります:

template<unsigned WIDTH, unsigned HEIGTH, typename T = int> class matrix { ... }

非常に単純明快で、テンプレート引数は行列のこのサイズを決定します。サイズは論理的に一定なので、一定になるように実装しました。しかし、 my を受け入れる関数を作成しようとするとmatrix、次の問題が発生します。

std::ostream& operator<<(std::ostream &os, const matrix &m){ ...}

そのように書かれていると、コンパイラはテンプレート引数の欠如を正当に反対します...しかし

std::ostream& operator<<(std::ostream &os, const matrix<unsigned, unsigned> &m){ ...}

このエラーをトリガーします:error: expected a constant of type 'unsigned int', got 'unsigned> int'

matrix型ではなく定数を期待するので、これも一種の真実です。

これに対処する方法は?私はこの問題に遭遇した最初の人ではないと確信しています.定数パラメータ化されたテンプレートを渡すというこの問題に取り組む最も「標準的な」方法は何ですか?

4

3 に答える 3

2

operator<<(ostream&)テンプレートクラスのオーバーロードをテンプレートとして宣言します。matrixこれはここでの明らかな解決策です

template<unsigned WIDTH, unsigned HEIGTH, typename T = int> 
class matrix 
{ 
public:
    T arr[WIDTH][HEIGTH];
};
template<unsigned WIDTH, unsigned HEIGTH, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGTH,T> &m)
{ 
    // formatting inserter of m  onto os
    return os;
}

int main()
{
    matrix<10, 10> m;
    std::cout << m << std::endl;
}

しかし、一般的に言えば、operator<<(ostream&)個人データへのアクセスが必要な場合 (通常はアクセスする必要があります)、それを友人として宣言することになります。remplate パラメーターを繰り返したくない場合は、operator<<(ostream&)非メンバーのフレンドをマトリックス クラスのスコープに配置します。

template<unsigned WIDTH, unsigned HEIGTH, typename T = int> 
class matrix 
{ 
     T arr[WIDTH][HEIGTH];
     friend std::ostream& operator<<(std::ostream &os, const matrix &m)
     { 
         // formatting inserter of m  onto os
         return os;
     }
};
于 2014-09-12T19:54:41.947 に答える
1

オプション1

クラスのスコープでフレンドoperator<<関数として宣言します。matrix

template<unsigned WIDTH, unsigned HEIGTH, typename T = int>
class matrix
{
    friend std::ostream& operator<<(std::ostream &os, const matrix& m)
    //                                                      ^^^^^^ plain name
    {
        return os;
    }
};

オプション #2

関数operator<<テンプレートも作成します。

template<unsigned WIDTH, unsigned HEIGHT, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGHT, T>& m)
//                                                      ^^^^^  ^^^^^^  ^
{
    return os;
}
于 2014-09-12T19:53:26.210 に答える
1

オーバーロードoperator<<もテンプレートである必要があります:

template<unsigned WIDTH, unsigned HEIGHT, typename T>
std::ostream& operator<<(std::ostream &os, const matrix<WIDTH, HEIGHT, T> &m){
  // ...
  return os;
}
于 2014-09-12T19:53:36.427 に答える