'function' in namespace 'std' 没有命名模板类型

'function' in namespace 'std' does not name a template type

使用 Rcpp 包在 R 中包含 C++,我尝试编译我的 C++ 文件。这是出现的错误:

'function' in namespace 'std' does not name a template type

经过调查,我被告知我的代码使用了一些仅在 C++ 11 中可用的功能。因此我需要在我的 Makevars 文件中添加一行。但是,我发现了一个小插图,上面写着 Makevars 不再是强制性的:Rcpp vignette。我该如何解决这个问题?

这是 C++ 脚本中不起作用的部分:

std::function<void(const state_type, state_type, const double)> eqsir2(const Rcpp::NumericVector theta) {
  return [&theta](const state_type &x, state_type &dxdt, const double t) {
    boost_array_to_nvec2(x, nvec);
    my_fun22(nvec,t,theta);
    nvec_to_boost_array2(nvec, dxdt);
  }

为了能够在 C++ 中使用 std::function,您必须通过

包含正确的 header
#include <functional>

代码库中的某处。

至于R端,你要告诉编译器你要使用C++11的特性。如果您只有通过 Rcpp::sourceCpp 包含的 .cpp 文件,则必须添加

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

到您的 .cpp 文件。

如果您正在编写 R 程序包(您引用的小插图就是为此目的),那么 src/Makevars 文件不再是使用 Rcpp 所必需的,但使用 CXX_STDsrc/Makevars 中是在编写包时请求 C++11 的建议方式。或者,您可以在 DESCRIPTION 中使用 SystemRequirements。引用自 Writing R extensions

In order to use C++11 code in a package, the package’s Makevars file (or Makevars.win on Windows) should include the line

CXX_STD = CXX11

Compilation and linking will then be done with the C++11 compiler.

Packages without a src/Makevars or src/Makefile file may specify that they require C++11 for code in the src directory by including ‘C++11’ in the ‘SystemRequirements’ field of the DESCRIPTION file, e.g.

SystemRequirements: C++11

If a package does have a src/Makevars[.win] file then setting the make variable ‘CXX_STD’ is preferred, as it allows R CMD SHLIB to work correctly in the package’s src directory.

此外,您必须确保返回函数的签名和 lambda 相同(参见 here)。就目前而言,您仅对其中一个使用引用。两者皆有可能,您只需要保持一致即可:

#include <Rcpp.h>
// [[Rcpp::plugins(cpp11)]]
#include <functional>

// [[Rcpp::depends(BH)]]
#include <boost/array.hpp>
typedef boost::array<double, 3> state_type;

// references
std::function<void(const state_type&, state_type&, const double)> eqsir2(const Rcpp::NumericVector theta) {
  return [&theta](const state_type &x, state_type &dxdt, const double t) {return;};
}

// no references
std::function<void(const state_type, state_type, const double)> eqsir(const Rcpp::NumericVector theta) {
  return [&theta](const state_type x, state_type dxdt, const double t) {return;};
}