[Rcpp-devel] operator<< issues

Iñaki Úcar i.ucar86 at gmail.com
Wed Mar 14 18:51:32 CET 2018


Hi all,

I'm not sure whether this is a bug or not, so I think this is the
right place to start with. Consider the following code:

Rcpp::sourceCpp(code='
  #include <Rcpp.h>
  using namespace Rcpp;

  // [[Rcpp::export]]
  void print_fun(Function x) {
    Rcout << x << std::endl;
  }

  // [[Rcpp::export]]
  void print_env(Environment x) {
    Rcout << x << std::endl;
  }
')

print_fun(function() {})
print_env(environment())

It compiles and the output from the functions are two addresses. So
far, so good. However, if we try the same for a data frame, the
compilation fails, so we need to define the operator<< as follows:

Rcpp::sourceCpp(code='
  #include <Rcpp.h>
  using namespace Rcpp;

  inline std::ostream& operator<<(std::ostream& out, const DataFrame& df) {
    out << "data.frame";
    return out;
  }

  // [[Rcpp::export]]
  void print_df(DataFrame x) {
    Rcout << x << std::endl;
  }
')

print_df(data.frame(x=1))

Now, it compiles and produces the output we defined. Once more, so
far, so good. Now the problem comes when we try to merge the two
examples above, that is:

Rcpp::sourceCpp(code='
  #include <Rcpp.h>
  using namespace Rcpp;

  inline std::ostream& operator<<(std::ostream& out, const DataFrame& df) {
    out << "data.frame";
    return out;
  }

  // [[Rcpp::export]]
  void print_df(DataFrame x) {
    Rcout << x << std::endl;
  }

  // [[Rcpp::export]]
  void print_fun(Function x) {
    Rcout << x << std::endl;
  }

  // [[Rcpp::export]]
  void print_env(Environment x) {
    Rcout << x << std::endl;
  }
')

The compilation fails again due to an ambiguous overload for Function
and Environment types, so that we need to define the operator<< for
these classes too in order to disambiguate and fix this. I suppose it
may happen for other classes too. Is this... expected? Desirable? At
the very least, it is confusing from my point of view.

Regards,
Iñaki


More information about the Rcpp-devel mailing list