std::pair<int,float> foo();  
     auto [a,b] = foo();  
     std::pair<int,float> foo();  
     int a;  
     float b;  
     std::tie(a,b) = foo();  
     std::tie(a,b) = std::make_pair(b,a);  
    int a[4] = { 1, 2, 3, 4};  
    auto [b,c,d,e] = a;      std::array<int, 4> a;  
    auto [b,c,d,e] = a;  
    std::map myMap;  
    ...  
    for (const auto & [k,v] : myMap) {  
    }  
   stuct X {  
    int theInt = 3;  
    float thePi = 3.14;  
   };  
   auto [a,b] = x;  
Unfortunately if you need to do something more fancy with your class it has to support the get<>() functions, and you need to reopen the std namespace to specialize std::tuple_size and std::tuple_element.
Given the following user defined type (note a and b here are private members):
   class Y {  
   public:  
    int foo() const {  
     return a;  
    }  
    float bar() const {  
     return b;  
    }  
   private:  
    int a = 3;  
    float b = 3.14;  
   };  
   template <int N> auto get(Y const &);  
   template <> auto get<0>(Y const & aY) {  
    return aY.foo();  
   }  
   template <> auto get<1>(Y const & aY) {  
    return aY.bar();  
   }  
   namespace std {  
    template<>  
    struct std::tuple_size<Y> {  
      static const size_t value = 2;  
    };  
    template<size_t I>  
    struct std::tuple_element<I, Y> {  
     using type = decltype(get<I>(declval<Y>()));  
    };  
   }  
   template<int N>   
   auto get(Y const & aY) {  
     static_assert(N==0 || N==1);  
     if constexpr (N == 0) {  
       return aY.foo();  
     } else if constexpr (N == 1) {  
       return aY.bar();  
     }  
   }  
 
 
3 comments:
Not able to use your class example .Has problem in calling get
int main()
{
Y aY;
auto [n,s] =get(aY);
}
No matching function for call to 'get'
Hi Hariom,
I think I see the problem; from your example you don't need to call get. Your main should be:
int main()
{
Y ay;
auto[n, d] = ay;
}
Or for a complete example: https://godbolt.org/g/PehWmk
Hope that helps!
Post a Comment