Link to the std :: get <1> function in the tuple header

How to get a link to the "get" function for a specific instance of a tuple?

My best attempt is given below but not compiled against g ++ 4.5.1

 #include <tuple> #include <string> typedef std::tuple<int,std::string> Tuple; auto t=(std::string& (Tuple&))(std::get<1,Tuple>); 

Compiler Error:

 a.cc:5: error: invalid cast to function type 'std::string&(Tuple&)' a.cc:5: error: unable to deduce 'auto' from '<expression error>' 

I would like to use a function reference as input for some stl algorithms. I'm actually a little surprised how non-trivial this is for me.

+4
source share
3 answers

The code below works for me. The trick is to use the typedef pointer function, not the typedef reference function. I am impressed that the compiler does not need all the parameters of the template, but it may possibly work out missing functions due to the overloaded type.

 #include <tuple> #include <string> typedef std::tuple<int,std::string> Tuple; typedef std::string& (*PFun)(Tuple&); PFun p1=(PFun)std::get<1U>; PFun p2=(PFun)std::get<1U,int,std::string>; 

In one line:

 auto p3=(std::string& (*)(Tuple&))std::get<1U>; 

Sorry to answer my own question. Sleeping at night can make a big difference.

+1
source

I think you want:

 namespace detail { template <std::size_t I, typename... Types> decltype(&std::get<I, Types...>) get_function(std::tuple<Types...>*) { return &std::get<I, Types...>; } } template <std::size_t I, typename Tuple> decltype(detail::get_function<I>((Tuple*)nullptr)) get_function() { return detail::get_function<I>((Tuple*)nullptr); } auto t = get_function<I, Tuple>(); 

The view is ugly. Of course, there is a better way, but all that I have now.

+3
source

After several experiments, I found that lambda expressions could be used:

 #include <tuple> #include <string> typedef std::tuple<int, std::string> Tuple; auto t = [] (Tuple& t) { return std::get<1> (t); }; 

If you need to use this a lot, you can always write a macro:

 #define REFERENCE_GET(N, Tuple) \ [] (Tuple &t) { return std::get<N> (t); } 
+2
source

All Articles