C ++ template for all pointers and template for all arrays

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:

// if I use this, the operator gets ambigous for arrays
template<typename T>
inline void operator&(T* p)
{
    cout << "general pointer operator: " << (*p) << "\r\n";
}
// this doesn't work because one cannot dereference void* 
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; // error: operator is ambigous
    obj & p; // works

    return 0;
}
+4
source share
3

++ 98 , - const .

#include <iostream>

struct Class
{
   template<typename T>
   void operator&(T* const &p)
   {
      std::cout << "general pointer operator " << (*p) << std::endl;
   }

   template<typename T, unsigned int N>
   void operator&(T (&)[N])
   {
      std::cout << "general array operator " << N << std::endl;
   }
};

int main()
{
   int myarr[1] = { 2 };
   int* p = myarr;
   Class obj;

   obj & myarr;
   obj & p;

   return 0;
}

:

general array operator 1
general pointer operator 2
+1

, , . , , , .

class cClass
{

public:
    template<class T, size_t N>
    void impl(T (&x)[N], std::true_type)
    {
        cout << "general array operator" << N << '\n';
    }

    template<typename T>
    void impl(T* p, std::false_type)
    {
        cout << "general pointer operator" << (*p) << '\n';
    }

    template<typename T>
    void operator&(T && x)
    {
        impl( std::forward<T>(x), std::is_array< typename std::remove_reference<T>::type >() );
    }

};
+4

, :

template<typename T>
void operator&(T*const& p)

. , .

+2

All Articles