解決通過存儲器分配的/陣列C++通過引用
我寫到現有LIB,處理結構bwords(見下面的代碼)一個接口,並想提供的可能性上調用一些校驗功能的bword本身,或上的字節串(一個bword構件):
#include <cstdio>
typedef unsigned char byte;
typedef unsigned short ushort;
typedef struct bwordSt { ushort nbLetters; byte *L; } bword;
template<typename T, size_t N>
ushort checkBwL(T (&wL)[N], ushort wSz) {
return 0;
}
ushort checkBwL(const byte* const &wL, ushort wSz) {
return 0;
}
ushort checkBw(const bword &bw) {
return checkBwL(bw.L, bw.nbLetters);
}
int main() {
ushort n;
byte fL[2] = {0, 1};
n = checkBwL(fL, 2); // calls the template function
bword bW = {2, new byte[3]};
bW.L[0] = 0; bW.L[1] = 1; bW.L[2] = 2;
n = checkBwL(bW.L, 3); // calls the non-template function
n = checkBw(bW); // calls the non-template function
return n;
}
字節字符串可以是巨大的,所以我想通過引用傳遞。我做到了。
我發現提供統一接口的唯一方法是複製模板(對於數組[byte])和超載(對於字節*)中的基本檢查函數(checkBwL)的代碼,這是醜陋的迫使我保持兩個基本相同(大)的功能。
任何方法?
SOLUTION
無需模板功能,只是不要忘了在參數規格的&
前const
const byte* const &wL
什麼checkBWL做什麼? –
@ NathanOliver:固定。 @理查德:很多東西,結構實際上比這更豐富。 – ExpertNoob1
爲什麼不從模板函數調用非模板函數? – VTT