Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable std::get support on class

What are the templates that I have to specialize to support std::get?

struct MyClass {
  int a;
};

template <const size_t I>
struct MyContainer {
  MyClass array[I];
};

What do I have to specialize to be able to do:

MyContainer<16> mc;
std::get<0>(mc);
like image 594
Matt Clarkson Avatar asked Apr 23 '13 15:04

Matt Clarkson


1 Answers

std::get is not a customization point for the standard library; the three function template overloads (for pair, tuple and array) do not explicitly allow for user-defined overloads, so 17.6.4.2.1p1 applies and adding a declaration of your own function template overload is undefined behaviour.

Note that get as an unqualified name is a customization point as of C++17; it is used by the structured binding declaration protocol to access tuple-like elements; but this is as an unqualified name, not the qualified name std::get.

That said, if you were to write:

namespace std {
   template<size_t I, size_t N> MyClass &get(MyContainer<N> &c) { return c.array[I]; }
}

and similarly for the rvalue reference and const reference overloads, your program would likely work as you expect.

However, there's little point seeing as the standard already supplies array:

template<size_t N> using MyContainer = std::array<MyClass, N>;
like image 65
ecatmur Avatar answered Sep 22 '22 14:09

ecatmur