Enable std::get support on class

后端 未结 2 1775
旧时难觅i
旧时难觅i 2021-02-14 13:13

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

struct MyClass {
  int a;
};

template 
struct MyContainer {
  MyClas         


        
2条回答
  •  孤街浪徒
    2021-02-14 14:11

    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 MyClass &get(MyContainer &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 using MyContainer = std::array;
    

提交回复
热议问题