Somebody
Somebody

Reputation: 175

Auto template for template type (C++)

I'm trying to make a simple class for matrices in C++. It looks like this:

template <int m, int n>
class mat {
    double data[n][m] {0.0d};

    // ...
}

My problem arose when I came to implementation of matrix multiplication. Basically, I need to introduce the third integer for the width of one of the input matrices and the resulting one. The definition of the method would've looked like this:

template<int p> mat<m, p> (mat::operator*)(mat<n, p> operand);

However, this requires p to be defined manually. So, is there a way to avoid a template specification?

Upvotes: 0

Views: 65

Answers (1)

nickie
nickie

Reputation: 5818

I don't think there's anything wrong with what you're suggesting. Perhaps I don't understand which template specification (instantiation?) is the one that bothers you. The following demo program works as I should expect:

#include <iostream>

template <int m, int n>
class mat {
 private:
  double data[n][m] {{0.0}};

 public:
  mat() {}
  static void demo() { std::cout << m << "*" << n << std::endl; }

  template<int p>
  mat<m, p> (operator*)(mat<n, p> operand) { return mat<m, p>(); }
};

int main() {
  mat<3, 4> a;
  mat<4, 5> b;
  a.demo();
  b.demo();

  // no explicit dimensions or template instantiation here
  auto c = a * b;
  c.demo();
}

The result (with Apple clang version 12.0.0 and with GNU C++ 8.3.0) is:

$ c++ -std=c++11 -Wall matmul.cpp
$ ./a.out
3*4
4*5
3*5

Upvotes: 1

Related Questions