Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Couldn't deduce template parameter while using dynamic object created with specified typename

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading