Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
How do I get a reference to a "get"-function for a specific tuple instance?
My best try is given below but does not compile 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>);
The compiler error is:
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 the function reference as an input to some stl-algorithms. I am actually a bit surprised on how non-trivial this seems to be for me.
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>();
Kind of ugly. Surely there's a better way, but that's all I have for now.
–
–
–
–
After a bit of experimenting, I've found that it is possible using lambda expressions:
#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 could always write a macro:
#define REFERENCE_GET(N, Tuple) \
[] (Tuple &t) { return std::get<N> (t); }
–
The code below works for me. The trick is to use a function-pointer typedef and not a function reference typedef.
I am impressed that the compiler does not need all template parameters, but can optionally work out missing ones through the overloaded function 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. A night sleep can make a big difference.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.