mirk
mirk

Reputation: 5510

reference to function std::get<1> in tuple header

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.

Upvotes: 4

Views: 2373

Answers (3)

mirk
mirk

Reputation: 5510

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.

Upvotes: 1

GManNickG
GManNickG

Reputation: 503805

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>();

Kind of ugly. Surely there's a better way, but that's all I have for now.

Upvotes: 3

Joe D
Joe D

Reputation: 2973

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); }

Upvotes: 2

Related Questions