解决通过存储器分配的/阵列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