unordered_map in a function argument

匆匆过客 提交于 2019-12-24 03:59:12

问题


Question

Why does using std::unordered_map as a function argument fail to compile (and how do I solve it)?

Example

This first function has the std::unordered_map as a function parameter, but fails to compile

library(Rcpp)

cppFunction(
  code = 'void test( std::unordered_map< std::string, std::string > um ) {

  }'
  , plugins = "cpp11"
  )

Whereas it's fine when declared in the body of the function

cppFunction(
  code = 'void test(  ) {
    std::unordered_map< std::string, std::string > um;
  }'
  , plugins = "cpp11"
)

Extra

I've used it successfully as a function argument here in an inline function in my spatialwidget library


Understanding the answer

Thanks to Ralf Stubner for the explanation. In summary, when making an Rcpp function callable by R, there has to be an equivalent R representation of the objects.

This code fails because there is no equivalent unordered_map in R

// [[Rcpp::export]]
void test( std::unordered_map< std::string, std::string > um ) {

}

This passes because it's not being called / exported to R

void test( std::unordered_map< std::string, std::string > um ) {

}

回答1:


You can use things like std::vector and std::list as function parameter and return values in functions that are callable from R because there exist appropriate specializations for Rcpp::as and Rcpp::wrap that convert between these C++ data structures and SEXPs that R knows about (both directions). Now R has no native map-like data type (although one can use named lists to some extend), which is (probably) why Rcpp has no inbuilt translation for std::unordered_map. There is no such limitation for functions that are only callable from C++, which is why your "extra" example works.

In principle you can define such conversion functions yourself, c.f. http://gallery.rcpp.org/articles/custom-templated-wrap-and-as-for-seamingless-interfaces/ and references therein. However, you first would have to decide on what type of data structure you want to use at the R-side.



来源:https://stackoverflow.com/questions/56456176/unordered-map-in-a-function-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!