ArrayRef

See c10/utils/ArrayRef.h.

Caution

IntArrayRef is an alias to ArrayRef<int64_t>.

ArrayRef<T> contains only two members: A const data pointer and a size. It is trivially copyable and assignable.

It has similar methods like std::vector. It also has two methods to get the front and back: front() and back(); both return a const reference.

Its method vec() converts itself to a std::vector by copying the underlying data.

Constructors

Data members

./code/array_ref/main.cc (Check size)
1struct Foo {
2  const int32_t *p;
3  size_t len;
4};
5
6static void TestSize() {
7  // Note: The data pointer in ArrayRef is const!
8  static_assert(sizeof(torch::ArrayRef<int32_t>) == sizeof(Foo), "");
9}

Default constructed

./code/array_ref/main.cc (Default constructor)
1static void TestDefaultConstructor() {
2  torch::ArrayRef<int32_t> a;
3  TORCH_CHECK(a.data() == nullptr);
4  TORCH_CHECK(a.size() == 0);
5  TORCH_CHECK(a.empty() == true);
6
7  TORCH_CHECK(a.begin() == nullptr);
8  TORCH_CHECK(a.end() == nullptr);
9}

From a single element

./code/array_ref/main.cc (From a single element)
1static void TestFromSingleElement() {
2  int32_t a = 10;
3  torch::ArrayRef<int32_t> b(a);
4  TORCH_CHECK(b[0] == a);
5  TORCH_CHECK(b.data() == &a);
6  TORCH_CHECK(b.size() == 1);
7}

From an initializer list

./code/array_ref/main.cc (From an initializer list)
1static void TestFromInitializerList() {
2  torch::ArrayRef<int32_t> a = {1, 2, 3};
3  TORCH_CHECK(a.size() == 3);
4  TORCH_CHECK(a[0] == 1);
5  TORCH_CHECK(a[1] == 2);
6  TORCH_CHECK(a[2] == 3);
7}

Other types of constructors

  • From two pointers: begin and end

  • From a pointer and a length

  • From a std::vector

  • From a container that has data() and size() methods

  • From a C array

  • From a std::array