所有指针的 C++ 模板和所有数组的模板

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

我正在寻找以下问题的解决方案:我有一个 class,我想在其中为所有类型的指针和所有类型的数组。在数组的实现中,我需要访问 arraysize,在指针的实现中,我必须能够对取消引用的对象执行某些操作。

正如here指出的那样,数组的方式非常清楚:

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

但是对于指针来说,以下都不起作用:

// 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);
}

是否有任何好的和干净的解决方案来实现运算符对任意数组和任意指针的不同行为?

这是一个完整的示例代码:

#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;
}

我不得不承认,我不知道为什么您的代码段无法正确编译。不管怎样,一个很好的旧标签调度解决方法似乎在起作用。

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 >() );
    }

};

C++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

修改代码最少的方案是:

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

这消除了歧义。我会自己发送标签。