简体   繁体   中英

Can I use a dynamic array as C++ template typename?

As for code below:

template<typename PatternType>
cl_int enqueueFillBuffer(
    const Buffer& buffer,
    PatternType pattern,
    ::size_t offset,
    ::size_t size,
    const VECTOR_CLASS<Event>* events = NULL,
    Event* event = NULL) const
{
    cl_event tmp;
    cl_int err = detail::errHandler(
        ::clEnqueueFillBuffer(
            object_, 
            buffer(),
            static_cast<void*>(&pattern),
            sizeof(PatternType), 
            offset, 
            size,
            (events != NULL) ? (cl_uint) events->size() : 0,
            (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL,
            (event != NULL) ? &tmp : NULL),
            __ENQUEUE_FILL_BUFFER_ERR);

    if (event != NULL && err == CL_SUCCESS)
        *event = tmp;

    return err;
}

The code can be compiled if the array length, 6 , is static designated.

queue.enqueueFillBuffer<float[6]>(buffer, nodes, 2345, 123456);

My question is how to make the length, 6, to be a variable and pass the compilation? Since dynamic array is supported in C99, sizeof(float[n]) can properly get the size (for the code sizeof(PatternType) ). But I cannot make the code below pass the compilation:

int n = 6;
queue.enqueueFillBuffer<float[n]>(buffer, nodes, 2345, 123456);

Consider using std::array . More generally, assume that an STL-like container will be passed to your method. For instance,

std::array<float, 6> nodes;
nodes[0] = ...

or

std::vector<float> nodes;
nodes.resize(6);
nodes[0] = ...

Then the lines

static_cast<void*>(&pattern),
sizeof(PatternType),

may be replaced with

static_cast<void*>(pattern.data()),
sizeof(typename PatternType::value_type) * pattern.size(), 

The compiler can then deduce the type, so calling the method then simply becomes

queue.enqueueFillBuffer(buffer, nodes, 2345, 123456);

No need for explicit template arguments.

The answer is no way to finish it. As for enqueueFillBuffer implementation, please refer: https://www.khronos.org/bugzilla/show_bug.cgi?id=1347 the max size of pattern supported is ulong16, 128 bytes.

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