numcpp.h
ファイル
#include "iostream"
namespace numcpp{
template<typename T>
struct Vector
{
std::vector<T> v;
};
template<typename T>
struct Matrix
{
std::vector<T> m;
//template<typename T>
friend std::ostream& operator << (std::ostream& out, const mf& mat);
};
typedef Vector<float> vf;
typedef Matrix<vf> mf;
}
coutが印刷できるように<<演算子をオーバーロードしようとしていますmf
。最初に、オーバーロード関数を直接mf
引数を取る友人にしようとしました。これを行ったのはMatrix
、議論として取り上げた場合、テンプレートを処理する必要があり、その方法がわからないためです。
numcpp.cpp
ファイル
#include "numcpp.h"
namespace numcpp{
std::ostream& operator << (std::ostream& out, const mf& mat)
{
//overloaded out here
return out;
}
}
main.cpp
#include "iostream"
#include "numcpp.h"
int main()
{
numcpp::mf inputs;
// inputs is filled with random numbers here
std::cout << inputs;
}
しかし、これはidentified mf is undefined
行の.hファイルにエラーを与えますfriend std::ostream& operator << (std::ostream& out, const mf& mat);
そこで、このアプローチをやめMatrix
、.cppファイルを変更せずにフレンド関数宣言を削除してみました。しかし、今は別のエラーが表示されますno operator << matches these operands
。これは、オーバーロードがnumcpp
名前空間で行われるため、名前空間のmain
外側にあるものが表示されないためだと思います。
通常必要なのは、ヘッダーファイルにテンプレートを定義することです。コンパイラがテンプレートのインスタンス化を行えるようにするには、呼び出しサイトで定義を使用できる必要があります。
可能であれば、最も簡単な方法は、定義をクラス定義に入れることです。
template<typename T>
struct Matrix
{
std::vector<T> m;
// using Matrix here is allowed and refers to the current instatiation, equivalent to writing Matrix<T>
friend std::ostream& operator << (std::ostream& out, const Matrix& mat) {
...
return out;
}
};
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加