【发布时间】:2023-03-12 09:57:01
【问题描述】:
class myclass{
//definitions here
};
myclass e;
int myarray[10];
/*
Do something...
*/
e = myarray;
为了使e = myarray 成为可能,我重载了 = 运算符。而且我必须得到传入数组长度的长度。
template <class T>
int getarrlen(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}
myclass::operator=(int obj[]) {
int len=getarrlen(obj);
//Do something...
}
但是getarrlen(obj)的返回值始终是1。
那么,重载函数中如何获取obj[]的长度呢?
顺便说一句,我也试过int size = *(&arr + 1) - arr;,也没用。
更新0: 为此:
template<typename T1, int size>
int getarrlen(T1(&)[size]) { return size; }
我有一个C2784 compiler-error in Visual Studio...奇怪... 更新1: @AlgirdasPreidžius 的链接提供的代码适用于主要功能,但不适用于我的代码:( 另外,为了更明显,我试过这个:
#include<iostream>
using namespace std;
int x[10];
//Begin of the copied code
template <std::size_t N>
struct type_of_size
{
typedef char type[N];
};
template <typename T, std::size_t Size>
typename type_of_size<Size>::type& sizeof_array_helper(T(&)[Size]);
#define sizeof_array(pArray) sizeof(sizeof_array_helper(pArray))
//End
void myv(int a[]) {
const std::size_t n = sizeof_array(a); // constant-expression!
cout << n << endl;
}
int main() {
int a[20] = {1,2,3,4,5};
myv(a);
}
代码不起作用。而且我尝试在void myv(int a[]) { 上方添加template <typename T, std::size_t Size>,但它也不起作用......
【问题讨论】:
-
您推导数组长度的模板错误。看看这个问题:How does this “size of array” template function work?
-
这行不通,您还需要将数组 size 作为模板参数。如何做到这一点已在互联网上展示并很容易找到。
-
myclass::operator=(std::pair<int*, size_t> ptr_and_len) -
@AlgirdasPreidžius MSCV 提供的链接中的答案似乎没有问题:Demo on CompilerExplorer
-
对
operator=使用与 sizeof 相同的模板重载(在修复后者之后...)
标签: c++ arrays operator-overloading