Skip to content

as_cpp<Enum> #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ README.html
.clangd/
cpp11test/compile_commands.json
cpp11test/src/Makevars
cpp11test/src/*.o
cpp11test/src/*.so
compile_flags.txt
inst/doc
vignettes/*_cache
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# cpp11 (development version)

* `as_cpp<E>()` now allows enumeration `E` (#52, @bkietz)

* `writable::logicals::operator=()` now allows C++ boolean values (#57, @romainfrancois)

* `list::const_iterator::operator*()` added so iterators could be used on list objects (#60, @romainfrancois)
Expand Down
13 changes: 13 additions & 0 deletions cpp11test/src/test-as.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,19 @@ context("as_cpp-C++") {
UNPROTECT(3);
}

test_that("as_cpp<enum>(INTSEXP)") {
enum Response { YES, NO, MAYBE };
SEXP r = PROTECT(Rf_allocVector(INTSXP, 1));

for (Response e : {YES, NO, MAYBE, static_cast<Response>(42)}) {
INTEGER(r)[0] = static_cast<int>(e);
auto x = cpp11::as_cpp<Response>(r);
expect_true(x == e);
}

UNPROTECT(1);
}

test_that("as_cpp<double>(REALSXP)") {
SEXP r = PROTECT(Rf_allocVector(REALSXP, 1));
REAL(r)[0] = 1.2;
Expand Down
12 changes: 12 additions & 0 deletions inst/include/cpp11/as.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@ is_integral<T> as_cpp(SEXP from) {
return T();
}

template <typename E>
using is_enum = typename std::enable_if<std::is_enum<E>::value, E>::type;

template <typename E>
is_enum<E> as_cpp(SEXP from) {
if (Rf_isInteger(from)) {
return static_cast<E>(as_cpp<typename std::underlying_type<E>::type>(from));
}

stop("Expected single integer value");
}

template <typename T>
using is_logical =
typename std::enable_if<std::is_same<typename std::decay<T>::type, bool>::value,
Expand Down