C++/CLIの仕様なのかフィールドだと初期化を受け付けないようなので、むりやり一行にしてみる
#include "pch.h"
#include <array>
using namespace System;
template<typename T>
static cli::array<T>^ initListToArray(std::initializer_list<T> list)
{
cli::array<T>^ ar = gcnew cli::array<T>(list.size());
pin_ptr<T> p = &ar[0];
memcpy(p, list.begin(), list.size() * sizeof(T));
//int i = 0; for (T t : list) { ar[i++] = t; }
return ar;
};
ref class test0402
{
public:
test0402()
{
arr1 = gcnew array<int> { 5, 4, 3, 1, 3, 2 };
}
// コンストラクタで
public: cli::array<int>^ arr1;
// 無理やりワンライナー
public: cli::array<int>^ arr2 = init_arr1(); private: static cli::array<int>^ init_arr1() { return gcnew cli::array<int> { 1, 3, 5, 7, 9 }; };
// テンプレートで
public: cli::array<double>^ arr3 = initListToArray({ 1.2, 3e4, -5.6 });
public: cli::array<String^>^ arr4 = initListToArray({ gcnew String("あいうえお"),gcnew String("かきくけこ") });
};
int main(array<System::String^>^ args)
{
test0402^ t = gcnew test0402();
for each (auto i in t->arr1) { System::Console::WriteLine(i); }
for each (auto j in t->arr2) { System::Console::WriteLine(j); }
for each (auto d in t->arr3) { System::Console::WriteLine(d.ToString(L"e2")); }
for each (auto s in t->arr4) { System::Console::WriteLine(s); }
return 0;
}