2017-09-18 36 views
0

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

无需模板功能,只是不要忘了在参数规格的&constconst byte* const &wL

+0

什么checkBWL做什么? –

+0

@ NathanOliver:固定。 @理查德:很多东西,结构实际上比这更丰富。 – ExpertNoob1

+1

为什么不从模板函数调用非模板函数? – VTT

回答

1

成功的关键是代表团:

#include <cstdio> 

typedef unsigned char byte; 
typedef unsigned short ushort; 
typedef struct bwordSt { ushort nbLetters; byte *L; } bword; 

ushort check_impl(ushort length, const byte* buffer) 
{ 
    // do your actual checking here 
    return 0; 
} 

template<typename T, size_t N> 
auto checkBw(T (&wL)[N], ushort wSz) -> ushort 
{ 
    return wSz == (N * sizeof(T)) && // assuming no null terminator 
    check_impl(wSz, reinterpret_cast<const byte*>(wL)); 
} 

ushort checkBw(const byte* const &wL, ushort wSz) { 
    return check_impl(wSz, wL); 
} 

ushort checkBw(const bword &bw) { 
    return check_impl(bw.nbLetters, bw.L); 
} 

int main() { 
    ushort n; 
    byte fL[2] = {0, 1}; 
    n = checkBw(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 = checkBw(bW.L, 3); // calls the non-template function 
    n = checkBw(bW);  // calls the non-template function 

    return n; 
} 
+0

事实上,不需要模板函数,正如NathanOliver所述。尽管我的C++ 11编译器不喜欢它,但你建议的技术非常有趣:test.cpp:14:36:error:'checkBw'函数使用'auto'类型说明符而不跟踪返回类型:auto checkBw (...感谢无论如何,这是要记住的东西。 – ExpertNoob1

+0

@ ExpertNoob1啊好的,我已经使用了一个C++ 14功能,我的歉意 –

+0

@ ExpertNoob1 ...和编辑,使其与C++ 11兼容。 –