Here is an exercise from C++ primer 5th edition:
"Exercise 16.26: Assuming NoDefault is a class that does not have a default constructor, can we explicitly instantiate vector<NoDefault>? If not, why not?"
Here is my guess:
Yes we can instantiate it:
template <typename T>
class Foo
{
public:
void func(){cout << x_.value_ << endl;}
private:
T x_;
};
class Bar
{
public:
Bar(int x) : value_(x){}
void print(){}
private:
int value_{};
template <class T>
friend class Foo;
};
extern template class Foo<Bar>; // instantiation declaration
template class Foo<Bar>; // instantiation definition
int main()
{
// Foo<Bar> f;
}
The code works fine but if I uncomment the line in main I get error as expected because Bar is not default-constructible.
If I use the same class Bar as an element type for std::vector it doesn't work:
extern template class vector<Bar>; // declaration ok
template class vector<Bar>; // instantiation: doesn't work?!
So why my
Foo<Bar>instantiation works but notvector<Bar>?What looks to me is that it is logical in
vector<Bar>not to work because an explicit instantiation definition instantiates all the members (even the ones not used) of the class template; and in this example among them the default constructor ofFoo<Bar>that implies a defaultctorof its element typeBar; the latter doesn't provide one; after allFoo<Bar>()normally is declared as a deleted member function becausex_doesn't have a default constructor. SO I don't know whyFoo<Bar>definition works?! Thank you.