mardi 28 août 2018

Initializing a C-style array with template function accepting callback

So, let's say I'm writing a function to initialize an array using a user-supplied callback per item. (I'm not, but let's suppose I am, for the purposes of a minimal example)

The cleanest way I can find to do this is the following:

#include <functional>

template<typename T, typename Y>
void PopulateArray(std::function<int(Y*)> callback, T &pArray)
{
  for (int i = 0; i < sizeof(pArray); ++i)
    int x = callback(&pArray[i]);
}

int main()
{
  uint64_t myArray[5];
  PopulateArray( (std::function<int(uint64_t*)>) [](auto x) {*x = 42; return 0; },
    myArray);
}

I have two issues with the code above.

1) For T to be an array type, there seems to be no way to decorate the parameter. (I can't say I want an array of type T, meaning I have to declare Y separately, even though they are both related to uint64_t.) I would prefer to declare a single T, with one parameter being a pointer to T and the other being an array of T.

2) The client code (in main), is forced to cast the lambda. Changing auto x to an explicit type doesn't seem to help matters.

Is there a resolution to #1 or #2 that might make the code more succinct or readable?

Code must compile with gcc, clang, and VS. I think C++11 is the newest standard I can use, although I'd be interested in C++14 solutions, as that would be a matter of upgrading our clang build process.

Aucun commentaire:

Enregistrer un commentaire