[Rcpp-devel] Dispatching based on SEXPTYPE
jj.allaire at gmail.com
Fri Nov 23 20:28:49 CET 2012
> Why do we need a macro here? Is it not possible to pass in method as a
> function? It seems like there must be a more elegant way to do
> dynamic dispatch.
As Dirk and Romain pointed out, we can't escape using the macro when we are
dealing with C-based SEXP since we don't know the type of an SEXP at
compile time. However, I think it's worthwhile pointing out that we can
avoid the macro entirely as long as we stay in C++ land (and we don't even
need to switch to CxxR!).
Here's the example we've been covering in this thread implemented within a
package that exposes both R and C++ interfaces to the function:
In the package, we first write "generic" C++ code that lives in a header
file (RcppAttributes.h) and can then be called by any C++ client (with
templates handling the generic dispatch at compile time):
Only when we need to call this function from R do we need to deal with
macros. Here's the R shim (very simple as a result of the macro):
Finally, here's what it looks like to call the function from both C++ and R:
The macro just collapses boilerplate syntax in the R shim. It's possible
that the variety of calling sequences will be so great (one vs. two
vectors, inclusion of values, return vs. no return, etc.) that capturing
them with macros is unrealistic, in which case you might just as well
include the switch/case directly in every call. I have a feeling though
that if you wanted to define dozens or even hundreds of functions that
macros would be up being a time saver and bug preventer.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Rcpp-devel