简体   繁体   中英

C++ pass memory allocated / array by reference

SOLVED

I am writing a interface to an existing lib that handles struct bwords (see code below), and would like to offer the possibility to call some check functions on the bword itself, or on a string of bytes (a bword member) :

#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;
}

The string of bytes can be huge, so I'd like to pass by reference. And I did it.

The only way I found to offer a uniform interface was to duplicate the code of the base check function (checkBwL) in a template (for arrays[byte]) and an overload (for byte*), which is ugly and forces me to maintain two basically identical (big) functions.

Any way around this ?

SOLUTION

No need for the template function, just don't forget the const before the & in argument specification const byte* const &wL

The key to success is delegation:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM