Skip to content
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
13 changes: 13 additions & 0 deletions cpp11test/src/test-as.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,19 @@ context("as_cpp-C++") {
UNPROTECT(1);
}

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

for (Response e : {Response::YES, Response::NO, Response::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
8 changes: 7 additions & 1 deletion inst/include/cpp11/as.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,13 @@ enable_if_integral<T, T> as_cpp(SEXP from) {
template <typename E>
enable_if_enum<E, E> as_cpp(SEXP from) {
if (Rf_isInteger(from)) {
return static_cast<E>(as_cpp<typename std::underlying_type<E>::type>(from));
using underlying_type = typename std::underlying_type<E>::type;
using int_type = typename std::conditional<
std::is_same<char, underlying_type>::value,
int, // as_cpp<char> would trigger undesired string conversions
underlying_type
>::type;
return static_cast<E>(as_cpp<int_type>(from));
}

stop("Expected single integer value");
Expand Down