[go: up one dir, main page]

First steps in using C++11 with Rcpp

Dirk Eddelbuettel — written Jan 9, 2013 — source

The recent release of the C++11 standard has brought a lot of attention to the new language features. Rcpp, as a CRAN package, follows CRAN policy in not (yet at least) supporting this standard for its purported non-portable status. As even the current g++ version does of course support C++11 by default, one still needs to explicitly enable C++11 support which we can do here from R prior to compiling:

Sys.setenv("PKG_CXXFLAGS"="-std=c++11")

Starting with version 0.10.3 of Rcpp, one can also enable this via the ‘cpp11’ plugin as shown below.

C++11 has a lot of nice features; the Wikipedia page is pretty thorough in describing them, and the recently-created ISO C++ website has a lot of additional material.

In a first example, we look at the auto keyword which allows the compiler to infer the type based on the assignment.

#include <Rcpp.h>

// Enable C++11 via this plugin (Rcpp 0.10.3 or later)
// [[Rcpp::plugins(cpp11)]]

// [[Rcpp::export]]
int useAuto() {
    auto val = 42;		// val will be of type int
    return val;
}

Testing it:

useAuto()
[1] 42

Another lovely feature are initialiser lists:

#include <Rcpp.h>

// [[Rcpp::export]]
std::vector<std::string> useInitLists() {
    std::vector<std::string> vec = {"larry", "curly", "moe"};
    return vec;
}

Testing it:

useInitLists()
[1] "larry" "curly" "moe"  

Lastly, we can appreciate the addition loops over ranges:

#include <Rcpp.h>

// [[Rcpp::export]]
int simpleProd(std::vector<int> vec) {
    int prod = 1;
    for (int &x : vec) {       // loop over all values of vec
       prod *= x;              // access each elem., comp. product
    }
    return prod;
}

This third example we can also look at:

simpleProd(1:5)
[1] 120

Again, we need to remind the reader that this still requires setting the -std=c++11 option for g++, and that CRAN will not allow this in uploads. Yet. That time will come though. And in the meantime, this can of course be used for non-CRAN projects.

tags: basics  c++11 

Related Articles