【发布时间】:2015-03-06 20:39:53
【问题描述】:
我正在寻找以下问题的解决方案:我有一个类,我想为所有类型的指针和所有类型的数组重载一个运算符(在此示例中为 &)。在数组的实现中,我需要访问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;
}
【问题讨论】:
-
我不明白您如何重载
operator&以返回 void。在我看来,&应该返回某种类型的指针,(或者可能是bool?) -
@abelenky 这是二元
operator&,bit-and运算符,而不是一元addressof运算符。它可以返回任何你喜欢的东西。 -
stackoverflow.com/q/28243371/3093378 了解您有歧义的原因