Param default std parameter value: vector initialization with Rcpp and C ++ 11?
I am trying to write a C ++ / Rcpp function that has an optional whos default argument should by default be a vector of length 1 with a value of 0. The following do not compile properly:
cppFunction("std::vector<int> test(std::vector<int> out = {0}) {
return out;
}")
I am getting the following error:
Error in cppFunction ("std :: vector test (std :: vector out = {1}) {\ n return out; \ n}"): function definition not found. addition: Warning messages: 1: No function found for Rcpp :: export attribute on fileee5f629605d7.cpp: 5 2: In sourceCpp (code = code, env = env, rebuild = rebuild, showOutput = showOutput ,: No Rcpp :: attributes export or RCPP_MODULE declarations found in the source
What is the correct way to do this?
source to share
You can wrap your main C ++ function in an R function that uses the default:
#include <Rcpp.h>
#include <vector>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
std::vector<int> cpp_test(const std::vector<int>& x)
{
return x;
}
/*** R
test <- function(X = c(0L))
{
cpp_test(X)
}
test()
test(c(1:5))
*/
which gives you
> Rcpp::sourceCpp('~/RcppFiles/cpp_test.cpp')
> test()
[1] 0
> test(c(1:5))
[1] 1 2 3 4 5
source to share
The package Rcpp
does not currently support exporting default values. There are several packages to improve this (including Rcpp11
), thought I have a solution Rcpp
with RCPP_MODULES
:
library("Rcpp")
cppFunction(plugins=c("cpp11"),'NumericVector test(std::vector<int> out) {
return wrap(out);
}
RCPP_MODULE(mod) {
function("test",&test,List::create( _["out"] = std::vector<int>({0})), "Simple description");
}', verbose=TRUE,rebuild=TRUE)
I am changing the return type, thought it works even if you return std::vector<int>
.
So how it works: it just creates a doc entry with a default, third argument for RCPP_MODULES
.
Only {0}
fails R
, so I need to explicitly specify std::vector
.
source to share