1

I'm trying to create a constant array in managed c++ and am getting stuck. I've searched around but haven't come across any good examples of how to do this.

What I'd like is the equivalent of:

const unsigned char myConstArray = {1,2,3,4,5,6};

Right now I'm staring at this:

literal array<Byte>^ myConstArray = gcnew array<Byte> { 1,2,3,4,5,6};

Which I gather is not right, since Visual Studio complains that I cannot use gcnew in a constant expression. Not sure where to go here, any help would be appreciated.

Cheers,

David

2 Answers 2

3

It will not work with the literal like that because:

A data member marked as literal must be initialized when declared and the value must be a constant integral, enum, or string type. Conversion from the type of the initialization expression to the type of the static const data-member must not require a user-defined conversion.

literal (C++ Component Extensions)

...however it is quite strange that literal is an an equivalent of static const but by using static const it compiles without errors.

Creating a read-only property is another way you could return the array:

ref class Test1 {
public:
    Test1() {
        myArray = gcnew cli::array<Byte> { 1, 2, 3, 4, 5, 6};
    }

    property cli::array<Byte>^ MyArray {
        cli::array<Byte>^ get() {
            return myArray;
        };  
    }

private:

    cli::array<Byte>^ myArray;

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

3 Comments

Hmm.. If I change it to static const I instead get warnings of "const/volatile qualifiers on this type are not supported". It does get past this point in compilation now. I suppose I can just make a regular array, make it private, and hope it doesn't get overwritten if there's no other way of doing this.
I hadn't thought of that! Thanks!
Worked great, and it actually simplified things a fair bit. Thanks again!
0
std::initializer_list<unsigned char>>({1, 2, 3,4,5,6};

I'm not sure if this applies to managed C++ but initializer lists are a C++11 construct that is inherently const and allows begin and end semantics to be applied but not array indexing. so as long as a ranged based for will work you can use this array.

1 Comment

Please explain what this block of code is. Right now, it's not very useful as an answer and in danger of deletion.

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.