I want to set default value in argument of function to Rcpp::Function argument.
Just simple assignment, Rcpp::Function func = mean
, is not possible. It returns error: no viable conversion from '<overloaded function type>' to 'Rcpp::Function' (aka 'Function_Impl<PreserveStorage>')
Or, I tried something like this: Rcpp::Function func = Function("mean")
, but again, it is not working. It returns warning message: Unable to parse C++ default value 'Function("mean")' for argument func of function
.
For example, I have my own function to maximum called maxC
:
// [[Rcpp::export]]
double maxC(NumericVector x) {
double max;
max = *std::max_element(x.begin(), x.end());
return max;
}
Now, I want to use it (maxC
) as default argument to another function, for example like this:
// [[Rcpp::export]]
double aggregate(NumericVector x, Rcpp::Function func = maxC) {
double agg;
agg = Rcpp::as<double>(func(x));
return agg;
}
But it doesn't work. Any suggestions? Thank you.
Once a default value is used for an argument in the function definition, all subsequent arguments to it must have a default value as well. It can also be stated that the default arguments are assigned from right to left.
Passing arguments by reference ¶ By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function).
A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument.
Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value. Let's understand this through a function student.
I do not believe you can set a default function in this way... The best that can be achieved is setting function to a NULL
value and then having the code execute the appropriate default later on. For example...
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector func_defaults(Rcpp::NumericVector x,
Rcpp::Nullable<Rcpp::Function> f = R_NilValue) {
if (f.isNotNull()) {
Rcpp::NumericVector res = Rcpp::as<Rcpp::Function>(f)(x);
return res;
}
Rcpp::Environment global_funcs = Rcpp::Environment::global_env();
Rcpp::Function mean_r = global_funcs["mean"];
return mean_r(x);
}
testing:
func_defaults(c(2.5,3,1))
# [1] 2.166667
func_defaults(c(2.5,3,1), mean)
# [1] 2.166667
func_defaults(c(2.5,3,1), median)
# [1] 2.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With