在函数中分配泛型变量 [英] assign generic type of variables in a function
问题描述
大家好,
我怎样才能在C
中为一个函数分配泛型类型参数,例如为了得到一个数组我使用以下,
Hello everyone,
How can i be able to make a function be assigned with a generic type parameter in C
for example in order to get the length of an array i use the following,
int n;
n = (sizeof(array)/ sizeof(array[0]));
i发现这个语句很有用,我想把它放在一个泛型函数中,但是一个数组可以是任何类型,如何让函数接收任何类型的任何一维数组。 br />
在此先感谢,
z3ngew
i find this statement useful and i want to put it in a generic function, but an array can be of any type, how to make the function receive any 1D array of any type.
Thanks in advance,
z3ngew
推荐答案
假设通过数组,你在谈论像这样的传统C风格数组:
Assuming that by array, you are talking about traditionnal C style array like this one:
int anArray[25];
如果您不需要编译时值,那么以下函数将能够计算出的数量任何数组中的项目。
If you don't need compile-time value, then the following function will be able to evaluate the number of items in any array.
template <typename T, int n> int len(T(&array)[n])
{
return (sizeof(array)/ sizeof(array[0]));
}
然后你可以得到这样的长度:
You can then get the length like that:
int n = len(anArray);
由于该代码只能编译数组而不是指针,因此模板使用起来更安全因为它不会用指针编译(或等效的 int not_really_an_array []
)。
此外,在模板函数,可以简单地写 return n;
但我复制了原始代码(包括所有多余的括号),以明确我做同样的事情。
Since that code will only compile for arrays and not pointers, the template is safer to uses as it would not compile with pointers (or the equivalent int not_really_an_array[]
).
Also, in the Template function, one could simply write return n;
but I have copied the original code (including all superfluous parenthesis) to make it clear that I do same thing.
你的解决方案是完美的但是ansi c不支持
your solution is perfect but ansi c does not support
template
所以这里是c中的解决方案
so here is the solution in c
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
你可以在这个函数中传递任何类型的数组,
感谢大家的努力,< br $> b $ b
z3ngew
you can pass any type of array in this function,
Thanks for your effort everyone,
z3ngew
这篇关于在函数中分配泛型变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!