can't use *this in a member function

Hello :)
I'm getting the error "no matching function for call to 'myArray<char, 3>::fill(myArray<char, 3>&, const char&)'" in the header file in line 43.
Here is my code:

myArray.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

template<class T, int N> class myArray {
public:
    myArray( );
    explicit myArray( T );
    
    T& operator[]( int n );
    T* dataPtr( int n );

    int size() const { return N; };
    void fill( const T& x );
    void printAll() const;
private:
    T elem[N] {};
};


template<class T, int N>
myArray<T,N>::myArray()
    : myArray{ T{} } {}

template<class T, int N>
myArray<T,N>::myArray(T t) {
    for(size_t i{}; i<N; ++i)
        elem[i] = t;
}

template<class T, int N>
T& myArray<T,N>::operator[](int n) {
    return elem[n];
}

template<class T, int N>
T* myArray<T,N>::dataPtr(int n) {
    return &(elem[n]);
}


// fills array with const T& val
template<class T, int N>
void myArray<T,N>::fill(const T& x) {
    fill(*this, x);     // uses the support function
}

// outputs myArray as a list
template<class T, int N>
void myArray<T,N>::printAll() const {
    std::cout << "[";
    for (unsigned int i=0; i<N-1; ++i)
        std::cout << elem[i] << ", ";
    std::cout << elem[N-1] << "]\n";
}

//-------------no class members-----------------------

// fills myArray with const T& val
template<class T, int N>
void fill(myArray<T,N>& r, const T& val) {
    for (size_t i{}; i<N; ++i)
        r[i] = val;
}


myArray-main.cpp
1
2
3
4
5
6
7
8
9
#include "myArray.h"

int main() {
    myArray<char,3> A;
    A.fill('d');
    A.printAll();
    
    return 0;
}


I don't understand why I can't use the dereference of 'this' in the member function fill().
The Code may not be very pretty but shouldn't it work though?
Thanks in advance ;)
Last edited on
The error clearly states that it can't find a function fill() that takes two parameters of the given types. It doesn't say anything about not being able to use the this pointer.
Move the definition of the non-member fill() above the definition of the member, or declare it.
Topic archived. No new replies allowed.