2017-09-18 37 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兼容。 –