A MATLAB interface to a C++ library does not support uninstantiated template classes. To work around this limitation, use a wrapper class to create instantiations for the data types that your project uses.
This example shows how to create a wrapper header file to use a template class with missing instantiations with MATLAB's Cpp Interface.
1.
***** Download the complete
used in this example. *****
1.
Example code with class Pairs
In this example, the class Pairs in this Templates.hpp header file is not instantiated.
// Header for Template class
#ifndef templates_Header
#define templates_Header
template <class T>
class Pairs {
public:
T val1;
T val2;
Pairs() : val1(0), val2(0) {}
Pairs(T first, T second) : val1(first), val2(second) {}
T getVal1() {
return val1;
}
T getVal2() {
return val2;
}
};
#endif
2. Create a wrapper header file
To include the Pairs class, create this wrapper header file TemplatesWrapper.hpp. Assume that Pairs supports int and double data types.
//Wrapper to instantiate template class Pairs
#include "Templates.hpp"
/* Data types that will be used for Pairs class. */
template class Pairs<int>;
template class Pairs<double>;
3. Generate the library definition for the MATLAB Interface
In this example, TemplatesWrapper.hpp and Templates.hpp are in the same folder.
clibgen.generateLibraryDefinition(["TemplatesWrapper.hpp","Templates.hpp"],"PackageName","Templates","Verbose",true)
4. Build the librarybuild(defineTemplates)
addpath('Templates')
5. Use the library
Create Pairs objects and call the getVal1 and getVal2 functions.
Pairs1 = clib.Templates.Pairs_int_(2,3);
Val1 = Pairs1.getVal1;
Pairs2 = clib.Templates.Pairs_double_(4.5,10.9);
Val2 = Pairs2.getVal2;
Pairs3 = clib.Templates.Pairs_int_(4.3,10.9);
Val2 = Pairs3.getVal2;