I have been learning tree data structure for a while. I tried to implement tree using templates. I came up with an error while calling some function for input. This is the fragment where I am getting error.
template <typename T> class Tree{
public:
T data;
vector<Tree<T>*>children;
Tree(T data){
this->data=data;
}
};
template <typename T> Tree<T>* inputtree(){
int element;
cout<<"Enter Root Node"<<endl;
cin>>element;
cout<<"Enter Total Number of children of Root :"<<endl;
Tree<T> * temp=new Tree<T>(element);
return temp;
}
int main(){
Tree<int>*root;
root=inputtree();
}
Note: I didn’t complete inputtree() function completely but still it is not functional without it’s content inside it.
I am getting error at line template <typename T> Tree<T>* inputtree().
Why am I getting this error. Is it syntactically wrong or I am making some other mistake.
I tried resolving it by removing the template feature and adding direct as return type. The issue was resolved. However I want my code to be implemented with template.
>Solution :
inputtree is a function template, not a regular functions. All of its template parameters (in this case just T) must be given a template argument. Either this argument is provided explicitly, or it is deduced from the function arguments.
In your case, this is not possible:
root = inputtree();
You are calling inputtree, but the compiler has no idea what the T is supposed to be. This cannot be inferred from the left hand side of the assignment.
To solve this problem, you would have to call:
root = inputtree<int>();
This provides the argument int for the template type parameter T explicitly.
Alternative Solution
You could also write a static member function:
template <typename T>
class Tree {
public:
// ...
// injected class name: Tree refers to Tree<T> here
static Tree* input() {
return /* ... */;
}
}
int main() {
// using auto, we don't repeat ourselves
auto root = Tree<int>::input();
}