No appropiate default constructor available when using template classes
I've got a template class like so:
template<class T>
class List
{
private:
struct node
{
T value;
node *next, *prev;
};
}
When creating instances of this List class with T 开发者_C百科= myClass* I have no problems, since value will be a pointer, but if it's an object, creating a node instance results in "No appropiate default constructor available" error, if this class has no default constructor.
I could solve this by changing T value to T *value, but I need to have copies of these values inside of the list, so that if they're removed outside of the list, they remain valid in here.
What would be the right way of aproaching this?
You could provide a constructor for node
that requires an instance of T
from which a copy can be constructed:
template<class T>
class List
{
private:
struct node
{
node(const T & init_value) : value(init_value) {}
T value;
node *next, *prev;
};
}
This would change the requirement on T
from default constructible to copy constructible. Any type in your list would require a copy constructor.
精彩评论