-3

I have two files that I would like to compile. They are as follows:

Array.hpp

template<class T> class Array 
{
    public:
        Array() {};
        ~Array() {};

        int width_, height_;
        std::vector<T> data_;

        template<typename U>
        void print(const Array<U>& inputArray);

        T* operator()(int x, int y);
}

Array.cpp

template<typename T> template<typename U>
void Array<T>::print(const Array<U>& inputArray)
{
    std::cout << ( *inputArray(0, 0) ) << std::endl; 
// ERROR: No matching function for call to object of type 'const Array<unsigned char>'
} 
template void Array<uint8_t>::print(const Array<uint8_t>& inputArray);
template void Array<uint8_t>::print(const Array<float>& inputArray);


template <typename T>
T* Array<T>::operator()(int x, int y)
{
    return &data_[0] + x + y*width_;
}
template uint8_t* Array<uint8_t>::operator()(int x, int y);
template float* Array<float>::operator()(int x, int y);

It is completely unclear to me why a call to the operator is throwing an error. The operator is clearly defined for both inputs types that are instantiated for function "print". Is it because the compiler is looking in the header files first and can't find an instance of the operator with the specified type. Defining the operator in the header file wouldn't do much good either. This (as far as my knowledge reaches) again would raise an error as there are two functions (operators) implemented in the header file with the same name but different return types.

What to do?

hhhhhhhhh
  • 113
  • 1
  • 8
  • ps. I am aware of the fact that the actual functioning of the code is utterly ridiculous. – hhhhhhhhh Jan 26 '17 at 14:53
  • 3
    Possible duplicate of [Storing C++ template function definitions in a .CPP file](http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file) – Mgetz Jan 26 '17 at 14:55
  • This doesn't address the question, but can't `print` just be a free function? – François Andrieux Jan 26 '17 at 15:00

2 Answers2

1

Your function

void Array<T>::print(const Array<U>& inputArray)

accepts const reference, while method that it is calling:

T* operator()(int x, int y);

is not const hence the error.

Slava
  • 43,454
  • 1
  • 47
  • 90
0

The first problem is void print(const Array<U>& inputArray); is not const but void Array<T>::print(const Array<U>& inputArray) const is. These are not the same functions. Perhaps you intended to make print static, since it doesn't use this?

The second problem is that the operator T* operator()(int x, int y); is not const but const Array<U>& inputArray is. inputArray can only call const methods.

There are many other problems with your code, but either of these is likely causing your error message.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87