如何在 Rcpp 的函数参数中将默认值设置为 Rcpp::Function? [英] How to set default value to a Rcpp::Function in argument of function in Rcpp?
问题描述
我想将函数参数中的默认值设置为 Rcpp::Function 参数.
I want to set default value in argument of function to Rcpp::Function argument.
仅仅简单的赋值,Rcpp::Function func = mean
,是不可能的.它返回错误:<代码>没有来自<重载的函数类型>"的可行转换到'Rcpp::Function'(又名'Function_Impl
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>')
或者,我尝试过这样的操作:Rcpp::Function func = Function("mean")
,但同样,它不起作用.它返回警告消息:无法解析 C++ 默认值 'Function("mean")' for argument func of function
.
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
.
例如,我有自己的最大函数叫做 maxC
:
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;
}
现在,我想使用它 (maxC
) 作为另一个函数的默认参数,例如:
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.
推荐答案
我不相信你可以用这种方式设置默认函数... 最好的办法是将函数设置为 NULL
value 然后让代码稍后执行适当的默认值.例如...
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);
}
测试:
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
这篇关于如何在 Rcpp 的函数参数中将默认值设置为 Rcpp::Function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!