Enable std::get support on class

后端 未结 2 1786
旧时难觅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 13:46

    I'm guessing you want to implement some algorithms that need access to arbitrary array-like containers using compile-time indices and therefor aim to use some function (like std::get) to uniformly perform that task?! In that case, it is the same business as making begin and end available for your class. You simply declare a function get in the namespace you declared your container class in, and let ADL do its jobs.

        template 
        MyClass& get (MyContainer& c) { return c.array[I]; }
    
        template 
        MyClass const& get (MyContainer const& c) { return c.array[I]; }
    

    In your algorithm you just use get (without the std namespace prefix) and ADL will call the correct function. So, for the standard structures like array, tuple and pair std::get is invoked and for your container the get function that you provided.

        int main(){
            std::array a {{0,1,2}};
            auto t = std::make_tuple(0.0, 1.0f, 2);
            auto p = std::make_pair('0', 4.4);
            MyContainer<3> c;
    
            std::cout << get<1>(a) << std::endl;
            std::cout << get<1>(t) << std::endl;
            std::cout << get<1>(p) << std::endl;
            std::cout << get<1>(c).a << std::endl;
    
            return 0;
        }
    

    Example

提交回复
热议问题