Skip to content

Upstreaming std::tuple<> support #1278

@andrjohns

Description

@andrjohns

Reporting an Issue

Over in the cmdstanr package we recently added support for passing std::tuple<> types between c++ and R by treating it as a List, and I was hoping to put together a PR to add it to Rcpp directly (I checked the issues and PRs but I couldn't find anything).

Should these overloads/specifications live in ListOf or VectorBase (or somewhere else completely)?

Also feel completely free to let me know if I'm handling the conversions in a way that's fundamentally wrong/inefficient!

The implementation is below, and just a note that the stan::math::apply is just c++11 implementation of std::apply:

#include <stan/math/prim/functor/apply.hpp>
#include <Rcpp.h>

namespace Rcpp {
  namespace traits {

    template <typename... T>
    class Exporter<std::tuple<T...>> {
      private:
        Rcpp::List list_x;

        template<std::size_t... I>
        auto get_impl(std::index_sequence<I...> i) {
          return std::make_tuple(Rcpp::as<T>(list_x[I].get())...);
        }

      public:
        Exporter(SEXP x) : list_x(x) { }
        std::tuple<T...> get() {
          return get_impl(std::index_sequence_for<T...>{});
        }
    };
  }

  template <typename... T>
  SEXP wrap(const std::tuple<T...>& x) {
    return stan::math::apply([](const auto&... args) {
      return Rcpp::List::create(Rcpp::wrap(args)...);
    }, x);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions