r - Warning when downcasting in Rcpp? -
i have rcpp function should take integervector input (as toint). want use on vector of integers, on vector of doubles integers (e.g. 1:4 of type integer 1:4 + 1 of type double).
yet, when used on real floating point numbers (e.g. 1.5), return warning or error instead of silently rounding values (to make them integers).
#include <rcpp.h> using namespace rcpp; // [[rcpp::export]] integervector toint(robject x) { return as<integervector>(x); } > toint(c(1.5, 2.4)) # warning [1] 1 2 > toint(1:2 + 1) # no need of warning [1] 2 3
rcpp sugar has need. here 1 possible implementation:
#include <rcpp.h> using namespace rcpp; // [[rcpp::export]] integervector fprive(const robject & x) { numericvector nv(x); integervector iv(x); if (is_true(any(nv != numericvector(iv)))) warning("uh-oh"); return(iv); } /*** r fprive(c(1.5, 2)) fprive(c(1l, 2l)) */ its output follows:
r> rcpp::sourcecpp('/tmp/fprive.cpp') r> fprive(c(1.5, 2)) [1] 1 2 r> fprive(c(1l, 2l)) [1] 1 2 warning message: in fprive(c(1.5, 2)) : uh-oh r> because warning object, can control via options("warn") whether want abort, print immediately, print @ end, ignore, ...
Comments
Post a Comment