Search⌘ K

- Solution

Explore how C++ templates work with classes and functions, focusing on implementing a template Array class with friend declarations. Learn why different template instances are treated as separate types and how friendship between them allows private member access, enhancing your understanding of template specialization and class interactions.

We'll cover the following...

Solution Review #

C++
//templateClassTemplateMethods2.cpp
#include <algorithm>
#include <iostream>
#include <vector>
template <typename T, int N>
class Array{
public:
Array()= default;
template <typename T2, int M> friend class Array;
template <typename T2>
Array<T, N>& operator=(const Array<T2, N>& arr){
static_assert(std::is_convertible<T2, T>::value, "Cannot convert source type to destination type!");
elem.clear();
elem.insert(elem.begin(), arr.elem.begin(), arr.elem.end());
return *this;
}
int getSize() const;
private:
std::vector<T> elem;
};
template <typename T, int N>
int Array<T, N>::getSize() const {
return N;
}
int main(){
Array<double, 10> doubleArray{};
Array<int, 10> intArray{};
doubleArray = intArray;
}

Explanation

...