简体   繁体   中英

Template with default parameters and specialization

I have this piece of code:

template <class T = double>
class Mat {

};

template <>
class Mat<double> {

};

/*****************************************************************************/
// main
/*****************************************************************************/
int main(int argc, char * const argv []) {

  Mat mat1;  // work

  Mat<Mat> mat2; // error

  return 0;

}

The compiler using -std=gnu++17 give me back on "Mat mat2":

"Use of class template 'Mat' requires template arguments"

I do not understand why.

Update:

Someone suggested me to use the notation

Mat<Mat<>>

However I pretty sure that the second empty <> should be superfluous in C++17

From what I read here , since C++17 you don't neet to provide <> if the type can be deduced from initializers, that's all. So you'd need an initializer if you want deduction without the <> .

So you either have to do something like that, as Quentin said in comments:

Mat<Mat<>> mat2;

Or define some constructors that will allow for type deduction. Here is how you could go about it:

template <class T = double>
class Mat
{
public:
   Mat(std::initializer_list<T> l) { for (const auto& v : l) std::cout << v << std::endl; }

   friend std::ostream& operator<< (std::ostream& os, const Mat<T>& mat) {
      os << "Mat object" << endl;
      return os;
   }
};

int main(int argc, char * const argv[]) {

   Mat mat1{ 1.0, 5.6 };  // T = double deduced from initializer list
   Mat mat2({ Mat{1.2, 3.6} }); // T = Mat<double> deduced from initizalizer

   return 0;
}

Result:

1
5.6
1.2
3.6
Mat object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM