'T' is not a valid template type argument for the 'T' parameter

I wrote a program to convert a sorted array to BST in C ++ using classes. I get the following errors:

error C2143: syntax error : missing ';' before '*'

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

error C2065: 'T' : undeclared identifier

error C2923: 'Binary_Search_Tree' : 'T' is not a valid template type argument for parameter 'T'

Below is my program:

template <class T>
class Binary_Search_Tree {
public:
    struct Bst_Node {
        T value;
        Bst_Node* left;
        Bst_Node* right;
    };

    Bst_Node* root;

    Binary_Search_Tree();

    Bst_Node* sortedarraytobst(T* A, int start, int end);
};

template <class T> Binary_Search_Tree<T>::Binary_Search_Tree() {
    root = nullptr;
    std::cout << "Constructor called" << std::endl;
}

template <class T> Bst_Node* Binary_Search_Tree<T>::sortedarraytobst(T* A, int start, int end) {

    if(start > end)
        return NULL;

    int mid = start + (end - start)/2;
    Bst_Node* newnode = new Bst_Node();
    newnode->value = A[mid];
    newnode->left  = sortedarraytobst(A,start,mid-1);
    newnode->right = sortedarraytobst(A,mid+1,end);

    return newnode;
}

int main()
{
    Binary_Search_Tree<int> tree;
    int Array[10] = {1,2,5,6,8,9,12};
    int n = sizeof(Array)/sizeof(Array[0]);
    tree.root = tree.sortedarraytobst(Array,0,n-1);

    return 0;
}

Request help in this regard. I find using templates very confusing.

+4
source share
2 answers

In the return value of the implementation, sortedarraytobstyou must replace Bst_Node*with typename Binary_Search_Tree<T>::Bst_Node*. When it is introduced as a return type, it is treated as "outside the class", so it cannot parse Bst_Node*.

+4
source

Binary_Search_Tree<T>::Bst_Node , :

template <class T>
Bst_Node* Binary_Search_Tree<T>::sortedarraytobst(T* A, int start, int end)
{/**/}

template <class T>
typename Binary_Search_Tree<T>::Bst_Node*
Binary_Search_Tree<T>::sortedarraytobst(T* A, int start, int end)
{/**/}

( ++ 11)

template <class T>
auto Binary_Search_Tree<T>::sortedarraytobst(T* A, int start, int end)
-> Bst_Node*
{/**/}
+2

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


All Articles