Tue, 20 Aug 2024

RcppMagicEnum 0.0.1 on CRAN: New Package!

Happy to announce a new package: RcppMagicEnum. It arrived on CRAN yesterday following the resumption of normal service following the CRAN summer break. RcppMagicEnum brings the magicenum library by Daniil Goncharov to R.

Modern C++ is powerful, but still lacks reflection. This may change with C++26 but until then this library can help. A simple example, also shown on the README is as follows (and can be called from R via Rcpp::sourceCpp() if the RcppMagicEnum package is installed):

// [[Rcpp::depends(RcppMagicEnum)]]

#include <RcppMagicEnum>

// define a simple enum class, it uses optional typing as well as optional assigned values
enum class Color : int { RED = -10, BLUE = 0, GREEN = 10 };

// [[Rcpp::export]]
void example() {
    // instantiate an enum value in variable 'val'
    auto val = Color::RED;

    // show the current value on stdout
    Rcpp::Rcout << "Name of enum: " << magic_enum::enum_name(val) << std::endl;
    Rcpp::Rcout << "Integer value of enum: " << magic_enum::enum_integer(val) << std::endl;
}

/*** R
example()
*/

It produces the following output (where the ‘meta-comment’ at the end ensure the included and created-by-sourcing function example() is also called):

> Rcpp::sourceCpp("miniex.cpp")

> example()
Name of enum: RED
Integer value of enum: -10
>

The plan to experiment some more with this and then see if we could possible make factor variables map to such enums and vice versa. Help and discussion input is always welcome, and could be submitted either on the rcpp-devel list or as an issue at the repo.

The short NEWS entry follows.

Changes in version 0.0.1 (2024-07-31)

  • Initial version and CRAN upload

If you like this or other open-source work I do, you can sponsor me at GitHub.

This post by Dirk Eddelbuettel originated on his Thinking inside the box blog. Please report excessive re-aggregation in third-party for-profit settings.

/code/rcpp | permanent link