<div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="im">Why do we need a macro here? Is it not possible to pass in method as a</div>
function? It seems like there must be a more elegant way to do<br>
dynamic dispatch.<br></blockquote><div><br></div><div>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!).</div>
<div><br></div><div>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:</div><div><br></div><div><a href="https://github.com/jjallaire/RcppAlgorithms">https://github.com/jjallaire/RcppAlgorithms</a></div>
<div><br></div><div>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):</div>
<div><br></div><div><a href="https://github.com/jjallaire/RcppAlgorithms/blob/master/inst/include/RcppAlgorithms.h">https://github.com/jjallaire/RcppAlgorithms/blob/master/inst/include/RcppAlgorithms.h</a></div><div><br></div>
<div>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):</div><div><br></div><div><a href="https://github.com/jjallaire/RcppAlgorithms/blob/master/src/Algorithms.cpp">https://github.com/jjallaire/RcppAlgorithms/blob/master/src/Algorithms.cpp</a></div>
<div><br></div><div>Finally, here's what it looks like to call the function from both C++ and R:</div><div><br></div><div><a href="https://github.com/jjallaire/RcppAlgorithms/blob/master/inst/examples/CallUnique.cpp">https://github.com/jjallaire/RcppAlgorithms/blob/master/inst/examples/CallUnique.cpp</a></div>
<div><br></div><div>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.</div>
<div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div></div>