以下代码无法编译,我试图弄清楚如何计算传递给函数的数组的大小,但似乎无法获得正确的语法。
我得到的错误是:
Error 1 error C2784: 'size_t getSize(T (&)[SIZE])' : could not deduce template argument for 'T (&)[SIZE]' from 'const byte []' 16 1 sizeofarray
这是源代码:
#include <cstdint>
#include <stdio.h>
template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
return SIZE;
}
typedef std::uint_fast8_t byte;
void processArray(const byte b[])
{
size_t size = getSize(b); // <- line 16 where error occurs
// do some other stuff
}
int main(const int argc, const char* argv[])
{
byte b[] = {1,2,3,4,5,6};
printf("%u\n", getSize(b));
processArray(b);
return 0;
}
最佳答案
如果你想让它工作,你还需要让 processArray 成为一个模板:
template <size_t size>
void processArray(const byte (&b)[size])
{
// do some other stuff
}
C++ 不允许按值传递数组。如果你有这样的功能:
void f(int a[5]);
你可能看起来像按值传递数组,但语言有一条特殊规则,表示这种形式的参数只是另一种说法:
void f(int *a);
所以数组的大小根本不是类型的一部分。这是从 C 继承的行为。幸运的是,C++ 有引用,您可以将引用传递给数组,如下所示:
void f(int (&a)[5]);
这样,您的数组的大小将得到保留。
现在,唯一剩下的技巧就是使函数通用,这样它就可以处理任何大小的数组。
template <size_t n> void f(int (&a)[n]);
现在,可以为您自动生成引用不同大小数组的新版本函数,并且可以通过模板参数访问大小。
关于c++ - 为什么这个模板函数调用在这个函数内部不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346236/