I am looking for a solution to the following problem: I have a class in which I want to overload the operator (in this example &) for all types of pointers and for all types of arrays. Inside the implementation for arrays, I need to have access to the array and inside the implementation for pointers. I have to do something with a dereferenced object.
As stated here , the path for arrays is pretty clear:
template<typename T, unsigned int N>
void operator&(T (&arr)[N])
{
cout << "general array operator: " << N << "\r\n";
}
But for pointers, none of the following works:
template<typename T>
inline void operator&(T* p)
{
cout << "general pointer operator: " << (*p) << "\r\n";
}
void operator&(void* p)
{
cout << "general pointer operator\r\n";
(*this) & (*p);
}
Is there a good and clean solution to achieve different operator behavior for arbitrary arrays and arbitrary pointers?
Here is the complete code example:
#include <iostream>
struct Class
{
template<typename T>
void operator&(T* p)
{
std::cout << "general pointer operator" << (*p) << std::endl;
}
template<typename T, unsigned int N>
void operator&(T (&arr)[N])
{
std::cout << "general array operator" << N << std::endl;
}
};
int main()
{
int myarr[5];
int* p = myarr;
Class obj;
obj & myarr;
obj & p;
return 0;
}
source
share