![](/img/trans.png)
[英]In function call, why doesn't nullptr match a pointer to a template object?
[英]Why doesn't this template function call work inside this function?
下面的代碼沒有編譯,我試圖弄清楚如何計算傳遞給函數的數組的大小,似乎無法使語法正確。
我得到的錯誤是:
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]);
現在,可以自動為您生成引用不同大小數組的函數的新版本,並且可以通過template參數訪問該大小。
作為函數的參數, const byte b[]
被視為與const byte *b
。 沒有關於調用函數的數組大小的編譯時信息。
要傳遞對數組的引用,您需要使processArray
成為模板並使用相同的技術。 如果未傳入引用,則參數為指針,指針類型不具有數組大小信息。
template<size_t size>
void processArray(const byte (&b)[size]) {
// ...
}
這是為什么你應該使用像getSize
而不是sizeof
這樣的函數模板來確定數組大小的規范示例 。
sizeof
,你已經得到了一個指針的大小,並沒有更明智。 這是什么錯誤? 它有一個函數參數const T arg[]
並認為這意味着arg
是一個數組。 不是。 這是來自C的不幸語法,它恰好等同於const T* arg
。 你得到一個指針。
這也是為什么有些人會錯誤地認為“數組是指針”的原因。 他們不是。 這只是這個特定的語法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.