0

In my class, I have the following declaration:

class OCLState {
    //Irrelevant stuff involving OpenCL contexts and command queues and so on...
    const cl_int16 values;

    OCLState(const std::array<int, 16> & _values);
}

So naturally, I need to initialize the vector when I create this object. Problem is, how do I translate _values into a form that values will accept as an initializer?

OCLState::OCLState(const std::array<int, 16> & _values) : values(
{ _values[0], _values[1], _values[2], _values[3] , _values[4] , _values[5] , _values[6], _values[7],
_values[8], _values[9], _values[10], _values[11] , _values[12] , _values[13] , _values[14], _values[15] }
) {
    //Irrelevant stuff involving setting up contexts and queues and so forth
}

This works, but it is EXTREMELY cumbersome and difficult to read. Is there a better way?

EDIT:

OCLState::OCLState(const std::array<int, 16> & _values) : values(array_to_vector(_values)) {

}

cl_int16 OCLState::array_to_vector(const std::array<int, 16> & in) {
    cl_int16 out;
    for (int i = 0; i < 16; i++) out.s[i] = in[i];
    return out;
}

This also works, but I consider it to be non-ideal. I'm looking for a way that doesn't involve writing helper methods for every single vector I might use when writing these programs.

2 Answers 2

1

One way to get around this without renouncing to the const-ness is by using the loved/hated reinterpret_cast. You could define your constructor as follows:

OCLState::OCLState(const std::array<int, 16> &_values) : 
    values(*reinterpret_cast<const cl_int16*>(&_values.front())) { }

Which produces the desired behaviour:

int main(int argc, char *argv[]) {
    OCLState S({0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15});
    std::cout << S.values.s[0] << "," << S.values.s[15] << std::endl;
}

prints > 0, 15

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm. This is ugly, but it adheres to the principle of what I'm trying to do. I'll consider it and decide whether it makes my life easier or not.
0

use can use std::copy (include < algorithm >) inside the constructor body

std::copy ( _values.begin(),_values.end(), &values.s[0]);

You'll have to remove the const from values though

Or wrap this code in a template function similar to your helper function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.