Search code examples
c++rcompiler-errorsrcpp

Rcpp: ambiguous overload for 'operator=' Matrix and List


The following Rcpp code is the minimal reproducible example for a much larger code that generates the identical compilation error. It seems that I cannot asign a numeric matrix to a list and the list then again to another matrix.

#include <Rcpp.h>
using namespace Rcpp;

//[[Rcpp::export]]
List return_a(NumericMatrix a, NumericMatrix b){
    //the function only returns the input matrix a
    List result(1);
    result(0) = a;
    return(result);
}


//[[Rcpp::export]]
List wrapper_cpp(NumericMatrix a, NumericMatrix b){
    //the function is a dummy wrapper for much more code
    List Step1(1);
    List results(1);    
    Step1 = return_a(a,b);
    a = Step1(0);   
    results(0) = a;
    return(results);
}

The code above gives the following compilation error that I shortened:

error: ambiguous overload for 'operator=' (operand types are 'Rcpp::NumericMatrix {aka Rcpp::Matrix<14>}' and 'Rcpp::Vector<19>::Proxy ...
a = Step1(0);

My real function is much more complex. I need to manipulate matrices in several loops and in each step the matrices are returned by each function within a list. I then need to extract these lists to manipulate the matrices further. How can this be done?


Solution

  • Besides the error that @Ralf already mentioned, you were simply trying too much. Sometimes we need an intermediate step as the template magic is ... finicky. The following works.

    Code

    #include <Rcpp.h>
    using namespace Rcpp;
    
    //[[Rcpp::export]]
    List return_a(NumericMatrix a, NumericMatrix b){
      //the function only returns the input matrix a
      List result(1);
      result(0) = a;
      return(result);
    }
    
    
    //[[Rcpp::export]]
    List wrapper_cpp(NumericMatrix a, NumericMatrix b){
      //the function is a dummy wrapper for much more code
      List results(1);
      List Step1 = return_a(a,b);
      NumericMatrix tmp = Step1(0);
      results(0) = tmp;
      return(results);
    }
    

    Output

    R> Rcpp::sourceCpp("~/git/stackoverflow/54771818/answer.cpp")
    R> wrapper_cpp(matrix(1:4,2,2), matrix(4:1,2,2))
    [[1]]
         [,1] [,2]
    [1,]    1    3
    [2,]    2    4
    
    R>