Default constructor defined by default arguments outside the class definition, why does this work? and what happens to the templates?

I know that this is a bad form and that the ad should have default values, but if you want to pamper me for a moment ... why does this compile? and what exactly is happening?

#include <iostream> using namespace std; class test { public: test(int n); }; test::test(int n = 666) { cout << n; } int main() { test t; cin.sync(); cin.ignore(); return 0; } 

Output: 666

.. how do templates affect the same piece of code?

 template <class T> class test { public: test(int n); }; template <class T> test<T>::test(int n = 666) { cout << n; } int main() { test<int> t; cin.sync(); cin.ignore(); return 0; } 

Error: no suitable default constructor

Thank you for your time!

+6
source share
2 answers

It seems that the C ++ specification specifically allows the first case and prohibits the second!

Quote from the C ++ specification (& section; 8.3.6 / 4):

For functions without a template, default arguments can be added to later function declarations in the same scope.

So it seems that for functions other than templates, you can enter the default arguments later. Not sure why this doesn't work for templates though!

+4
source

The first case is permitted by the standard; I remember what @Johannes asked and answered @ Nawaz. (Edit: Here is a related question ).

The reason for not allowing the template version is because the template functions are only called with an explicit instance. In your case, the compiler looks at the declaration as

 test<int> t; 

-> Edit : it may be different from the compiler. In gcc, it works fine . <-

Why this may not work in the compiler may be . Since you are not explicitly creating an instance as t(N) , the compiler will not be able to resolve test<T>::test(int n = 666) . Thus, it searches for a default constructor without an argument that is not found; leading to an error.

+1
source

Source: https://habr.com/ru/post/893437/


All Articles