how to define a friend template function of a template class

41 views Asked by At

I've a Template Class array_T which is a general purpose array and a Template function linear search TEMPLATE.h and its declared as friend for the class arrayTemplate.h so it could be able to use the class's member function getArraySize() and the class's data member a which is a dynamic allocation array

arrayTemplate.h

    #ifndef arrayTemplate
    #define arrayTemplate
    #include"linear search TEMPLATE.h"
    #include<iostream>
    using namespace std;

    template <class T>
class array_T  {

private:
    T *a;
    int arraySize;

public : 
    friend void linearSearch(array_T object);

    array_T(int s) {
        arraySize = s;
        a = new T[arraySize];

        for (int i= 0; i < arraySize; ++i) {
            a[i] = 0;
        }
    }

    ~array_T() {
        delete[]a;
    }

    void setArray() {
        for (int  i=0; i < arraySize; ++i) {
            cout << "Enter the elements of the array " << endl;
            cin >> a[i];
        }
    }

    void getArray() {
        for (int  i=0; i < arraySize; ++i) {
            cout << a[i] << endl;
        }
    }

    int getArraySize() {
        return arraySize;
    }


};
#endif

linear search TEMPLATE.h

#include"arrayTemplate.h"
#include<iostream>
using namespace std;

template <class T>
//void linearSearch(T desiredData, int arraySize, T *elemnts) {
void linearSearch(array_T<T> object , T desiredData) {
    int arraySize = object.getArraySize();
    int loc = -1;
    int i = 0;
    for (i = 0; i < arraySize; ++i) {

        if (object.a[i] == desiredData) {
            loc = i;
            break;
        }
    }

    if (loc > 0) {
        cout << "the Item is found at position " << i + 1 << endl;
    }
    else {
        cout << "the item is not found ";
    }

}

main.cpp

  #include"arrayTemplate.h"
   #include"linear search TEMPLATE.h"
    #include<iostream>
    using namespace std;



int main() {

    array_T<int> myArray(7);
    myArray.setArray();

    linearSearch(myArray,50)

return 0 ; 
}

these are the errors i got

linear search template.h(8): error C2065: 'array_T': undeclared identifier

linear search template.h(8): error C2065: 'object': undeclared identifier

linear search template.h(8): error C2275: 'T': illegal use of this type as an expression

linear search template.h(6): note: see declaration of 'T'

linear search template.h(8): error C2146: syntax error: missing ')' before identifier 'desiredData'

main.cpp(14): error C2660: 'linearSearch': function does not take 2 arguments

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

0

There are 0 answers