c++ - 在函数参数中区分数组和指针 - 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: %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
推荐阅读
- java - 在 JPA nativeQuery 中计数和分组
- laravel - 如何在 Laravel 中使用具有多重身份验证的验证电子邮件?
- keras - 如何在 keras 中微调加载的模型?
- python - Scipy Optimize ValueError:解包的变量太多
- reactjs - 更改悬停的图表旁边所有图表的背景颜色
- laravel - Laravel 依赖注入在服务中不起作用
- angular - 为什么显示行,但我的材料表中没有显示数据?
- spring - 在 Spring Jpa 页面结果中隐藏属性
- react-native - 按 RN 应用程序上的后退箭头不会将连接的组件刷新到 Redux 商店
- java - 编辑日志消息 - LogEventFactory vs RewriteAppender