Skip to content
Prev 2270 / 10988 Next

[Rcpp-devel] Exposing constructors with same number of arguments with different types using Rcpp Modules

Hi Dirk,

many thanks for your quick reply. Maybe something like the below could
work? The different constructor specifications are defined in the list
ClassName at constructors, but I coudln't find where R decides which of
these functions to call.

Thanks again,
Jelmer

overloaded.func <- function( x1, x2 ) {
    f1 <- function( x1, x2 ) {
        cat( "f1\n" )
        return( x1 + x2 )
    }

    f2 <- function( x1, x2 ) {
        cat( "f2\n" )
        return( nchar(x1) + nchar(x2) )
    }

    f3 <- function( x1, x2 ) {
        cat( "f3\n" )
        return( x1 + nchar(x2) )
    }

    f4 <- function( x1, x2 ) {
        cat( "f4\n" )
        return( x1 + x2 )
    }

    # add different versions to list
    func.list <- list( f1, f2, f3, f4 )

    # define argument types of f1, f2, f3
    argstypes <- list(
        c( "numeric", "numeric" ),          # input arguments of f1
        c( "character", "character" ),      # input arguments of f2
        c( "numeric", "character" ),        # input arguments of f3
        c( "numeric", "integer" ) )         # input arguments of f4

    # get types of input arguments supplied by user
    inputtypes <- c( class( x1 ), class( x2 ) )

    # get index of function that agrees with these arguments
    findex <- which( sapply( argstypes, function(type) {
all(inputtypes == type) } ) )

    # if there is such a function evalute it, otherwise return error
    if( length( findex ) == 0 ) {
        stop(paste( inputtypes, sep=' '  ))
    }
    else {
        return( func.list[[ findex ]]( x1, x2 ) )
    }
}


overloaded.func( 3, 3 )             # f1
overloaded.func( "test", "test" )   # f2
overloaded.func( 3, "test" )        # f3
overloaded.func( 2, 3L )            # f4
overloaded.func( "test", 3 )        # error
On Fri, May 13, 2011 at 18:58, Dirk Eddelbuettel <edd at debian.org> wrote: