在函数参数-C++中区分数组和指针



这是我一直在努力解决的一个问题。我在下面尝试的代码也没有编译

问题是:如何区分函数参数中的指针和固定数组?

// Concepts for the Array I have tried but not succeeded.
template <size_t length, typename type>
const unsigned int len(type arg[static length]) { return length; }
template <size_t length, typename type>
const unsigned int len(type(&)[length]) { return length; }
// This works for Arrays & Pointers
// but should be less prioritized over the function that detects the Array
template <typename type> const unsigned int len(type* arg) { return sizeof(*arg); }

我知道数组&指针在传递到函数中时基本上是相似的,但它提出了一个问题:难道没有办法区分它们吗?

从语法上来说是的,但除此之外还有什么其他方式呢?

不管怎样,谢谢你通读,并为你的回应欢呼。

这种方法适用于我:

#include <stdio.h>
template<typename T, int size> unsigned int len(const T(&)[size]) {printf("The number of items in your array is:  %in", size); return size;}
template<typename T> unsigned int len(const T * p) {printf("The size of the item your pointer points to is: %zun", sizeof(*p)); return sizeof(*p);}
int main(int, char **)
{
int myArray[10];
int * myPointer = myArray;
(void) len(myArray);
(void) len(myPointer);
return 0;
}

当我运行它时,它会打印出来:

The number of items in your array is:  10
The size of the item your pointer points to is: 4

只有当数组是通过引用传递的时,才能推导出数组的长度,否则它会衰减到指针:

template<typename T, std::size_t length>
constexpr std::size_t len(const T(&)[length]) { return length; }
//                               ^^^
template<typename T>
constexpr std::size_t len(const T *&p) { return sizeof *p; }
//                                ^^^

完整演示:

#include <cstdlib>
template<typename T, std::size_t length>
constexpr std::size_t len(const T(&)[length]) { return length; }
template<typename T>
constexpr std::size_t len(const T *&p) { return sizeof *p; }
#include <iostream>
int main(int, char **)
{
const int array[7] = {};
const int *pointer = array;
std::cout << "array has " << len(array) << " itemsn"
<< "and pointer is to " << len(pointer) << " charsn";
}

最新更新