首页 > 解决方案 > 在函数参数中区分数组和指针 - 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); }

我知道数组和指针在传递给函数时基本相似,但它提出了一个问题:有没有办法将它们区分开来?

语法上是的,但除此之外还有什么其他方法?

无论如何,感谢您阅读并为您的回复欢呼。

标签: c++

解决方案


这种方法对我有用:

#include <stdio.h>

template<typename T, int size> unsigned int len(const T(&)[size]) {printf("The number of items in your array is:  %i\n", size); return size;}
template<typename T> unsigned int len(const T * p) {printf("The size of the item your pointer points to is: %zu\n", 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

推荐阅读