Skip to content

Commit 628ae8f

Browse files
committed
UPDATE AS.HPP
1 parent b1d8858 commit 628ae8f

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

inst/include/cpp11/as.hpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#pragma once
22

33
#include <cmath> // for modf
4+
#include <complex> // for std::complex
45
#include <initializer_list> // for initializer_list
56
#include <memory> // for std::shared_ptr, std::weak_ptr, std::unique_ptr
67
#include <stdexcept>
@@ -333,4 +334,24 @@ enable_if_convertible_to_sexp<T, SEXP> as_sexp(const T& from) {
333334
return from;
334335
}
335336

337+
// Specialization for converting std::complex<double> to SEXP
338+
template <>
339+
inline SEXP as_sexp(const std::complex<double>& x) {
340+
SEXP result = PROTECT(Rf_allocVector(CPLXSXP, 1));
341+
COMPLEX(result)[0].r = x.real();
342+
COMPLEX(result)[0].i = x.imag();
343+
UNPROTECT(1);
344+
return result;
345+
}
346+
347+
// Specialization for converting SEXP to std::complex<double>
348+
template <>
349+
inline std::complex<double> as_cpp(SEXP x) {
350+
if (TYPEOF(x) != CPLXSXP || Rf_length(x) != 1) {
351+
throw std::invalid_argument("Expected a single complex number.");
352+
}
353+
Rcomplex c = COMPLEX(x)[0];
354+
return {c.r, c.i};
355+
}
356+
336357
} // namespace cpp11

0 commit comments

Comments
 (0)