Rcpp Armadillo: RStudio says “exp” is ambiguous

允我心安 提交于 2019-12-12 18:28:42

问题


I'm trying out Rcpp / RcppArmadillo in RStudio with the following code:

#include <RcppArmadillo.h>

//[[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using std::exp;
using std::log1p;

// [[Rcpp::export]]
arma::vec log1pexp(arma::vec x) {
  for(int ii = 0; ii < x.n_elem; ++ii){
    if(x(ii) < 18.0){
      x(ii) = log1p(exp(x(ii)));
    } else{
      x(ii) = x(ii) + exp(-x(ii));
    }
  }
  return x;
}

RStudio says the calls to exp are ambiguous. I've tried calling std::exp in the code instead of using std::exp but have no success. The code compiles without warnings through Rcpp::sourceCpp('filename.cpp'). If I cast (float)x(ii) in the code the warning disappears, but not if I cast (double)x(ii).

Any insight appreciated, I'm pretty inexperienced with both C++ and RStudio.

Picture of what's going on


回答1:


For starters, don't do

using namespace Rcpp;
using std::exp;
using std::log1p;

If in doubt, be explicit. Your code then becomes

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]

// [[Rcpp::export]]
arma::vec log1pexp(arma::vec x) {
    for(size_t ii = 0; ii < x.n_elem; ++ii){
        if(x(ii) < 18.0){
            x(ii) = std::log1p(std::exp(x(ii)));
        } else{
            x(ii) = x(ii) + std::exp(-x(ii));
        }
    }
    return x;
}

and compiled without a hitch (after I also changed int to size_t for the loop) -- and without an issue in the RStudio IDE (using a fairly recent daily, 1.0.116).

There are

  • std::exp() in the standard library, using double
  • Rcpp::exp() from Rcpp Sugar, using our vectors
  • arma::exp() from Armadillo using its vectors

and I always found it easiest to be explicit.

Edit: I had missed log1p. Prefixing it with std:: also requires C++11. Two changes made.



来源:https://stackoverflow.com/questions/40997722/rcpp-armadillo-rstudio-says-exp-is-ambiguous

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