1

スパース行列を効率的に操作できるクラスSparse_Matrixがあります。

Upper、Identityなどの特定の(慣用的な)キーワードを使用して、特定のマトリックスをインスタンス化したいと思います。

これは私のクラス宣言(名前空間マトリックス)です

template <typename T>
class Sparse_Matrix
{

  private:
  int rows;
  int cols;
  std::vector<int> col;
  std::vector<int> row;
  std::vector<T> value;
  ...

事前に初期化されたオブジェクトを取得する方法はありますか?

 Sparse_Matrix<int> = Eye(3);

3行3列の単位行列を返します。

私はコンストラクターのイディオムを見てきましたが、それらは私のクラスと互換性のない静的なタイプのソフトを必要とします(私は提案を受け入れていますが)。

私もこのコードを試しました:

template <typename T>
Sparse_Matrix<T> Eye(int size)
{
  Sparse_Matrix<T> ma;
  ma.IdentityMatrix(size);
  std::cout << "Eye!" << std::endl;
  return ma;
}

..。

Sparse_Matrix<int> blah = Eye(10);

しかし、役に立たない。

ありがとうございました、

SunnyBoyNY

4

2 に答える 2

2

Having a function that constructs your object is a good strategy. In your example, one solution would be specifically to tell Eye the type:

Sparse_Matrix<int> blah = Eye<int>(10);

Sometimes these functions are static within the class for clarity:

template<typename T>
class Sparse_Matrix
{
public:
    static Sparse_Matrix<T> Eye(...) {...}
};

In this case, you would call:

Sparse_Matrix<int> blah = Sparse_Matrix<int>::Eye(10);
于 2013-01-11T02:36:37.767 に答える
2

C ++には、式の使用方法に基づいてテンプレートパラメータを推定できる場所が1つだけあります。それは、ユーザー定義の変換演算子です。

struct Eye
{
    int size;
    explicit Eye(int requestedSize) : size(requestedSize) {}

    template<typename T>
    operator SparseMatrix<T>() const { SparseMatrix<T> ma; ma.IdentityMatrix(size); return ma; }
};

今、あなたは書くことができます

Sparse_Matrix<int> blah = Eye(10);
于 2013-01-11T02:41:52.103 に答える