c++ - Rcpp:构造模板化函数

标签 c++ rcpp

我有以下 MWE。它包含一个具有两个成员的类,一个整数和一个字符串。使用函数first,我创建了该类的一个对象并返回一个指向它的指针。在 second_intsecond_str 中,我输出了两个成员。

鉴于 second_intsecond_str 具有或多或少相同的功能,对我来说,对它们进行模板化似乎是显而易见的。考虑到我的 MWE,这可以在 Rcpp 中完成吗?

class C{
public:
  std::vector<int> i_vec;
  std::vector<std::string> s_vec;

  C(){
    i_vec.push_back(0);
    s_vec.push_back("R");
  }
};

// [[Rcpp::export]]
XPtr<C> first()
{
  XPtr<C> p(new C, true);
  return(p);
}

// [[Rcpp::export]]
void second_int(XPtr<C> p)
{
  Rcout << p->i_vec[0] << "\n";
}

// [[Rcpp::export]]
void second_str(XPtr<C> p)
{
  Rcout << p->s_vec[0] << "\n";
}

最佳答案

这里不能直接使用模板,但是我们可以用它来完成我认为你想要的!让我们考虑一下您已编写的内容以及您希望直接编写的内容。

你有:

// [[Rcpp::export]]
void second_int(XPtr<C> p)
{
  Rcout << p->i_vec[0] << "\n";
}

// [[Rcpp::export]]
void second_str(XPtr<C> p)
{
  Rcout << p->s_vec[0] << "\n";
}

您想要的(这不是有效的 C++)是这样的:

// [[Rcpp::export]]
template< membername member_to_extract >
void second(XPtr<C> p)
{
  Rcout << p->member_to_extract[0] << "\n";
}

/**
 * we would like to call it like this:
 * second<i_vec>(p) (to get the int value)
 * second<s_vec>(p) (to get the str value)
 */

为什么这不起作用?好吧,检查http://en.cppreference.com/w/cpp/language/template_parameters ,我们看到您不能将变量名称作为模板参数传递!所以这种做法注定会失败。 (注意:您可以为此使用宏,这可能是您正在寻找的解决方案!)

但是,虽然您的函数参数和返回类型相同,但它们的行为完全取决于您想要使用的类型。如果您要在已经模板化的上下文中使用这些函数,那么最好获得第二个和第二个接口(interface)!

模板特化来救援!

// generic template. We need something that fails to compile
// so that second<int> and second<std::string> are the only
// specializations the compiler will allow us to use.
template< typename T >
void second(XPtr<C> p)
{
  static_assert(false, "second can't be used with this type.");
}

template< >
void second<int>(XPtr<C> p)
{
  Rcout << p->i_vec[0] << "\n";
}

template< >
void second<std::string>(XPtr<C> p)
{
  Rcout << p->s_vec[0] << "\n";
}

我想这就是你想要的?请注意,如果您的平台不是行缓冲的,您可能需要使用 std::endl 而不是“\n”,因为它会强制刷新(这可能是您想要的行为)。

编辑:部分特化 -> 模板特化

关于c++ - Rcpp:构造模板化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184442/

相关文章:

c++ - Xerces C++ SAX 解析问题 : expected class-name before '{' token

c - 从 R 中的 .C 调用返回输出

c++ AVX512 内部相当于 _mm256_broadcast_ss()?

c++ - 如何仅根据第二个字符串对字符串 vector 的 vector 进行排序

c++ - 我可以在 RCpp 中使用单例模式吗?

c++ - 使用 Rcpp 模块公开 C++ 类

c++ - RInside 中使用 null 环境已失效错误

r - 将 R::vector 转换为 std::vector

c++ - C++ 中是否有标准的循环整数类?

c++ - 从 vector 中提取子 vector 而不复制