Use Function and Member Function Templates
MATLAB® supports C++ function and member function templates. The C++ interface generates a MATLAB function overload for each function template instantiation using a valid MATLAB name based on the C++ function name.
Display Help for Interface
Suppose that you have this C++ header file that defines a function template
show
. To run this example, follow the instructions in Build Interface for Overloaded Functions Example to generate a
MATLAB interface named liboverload
.
When you display help for liboverload
, you see three calling syntaxes
for show
.
help clib.liboverload.show
clib.liboverload.show Representation of C++ function show. clib.liboverload.show(a) Input Arguments a int32 clib.liboverload.show Representation of C++ function show. clib.liboverload.show(a) Input Arguments a double clib.liboverload.show Representation of C++ function show. clib.liboverload.show(a) Input Arguments a read-only clib.liboverload.A
Call show
in MATLAB
If you type:
var = pi; clib.liboverload.show(var)
then MATLAB chooses the signature with input type double
.
Build Interface for Overloaded Functions Example
This C++ code defines a function template show
and provides
instantiations for types int
, double
, and
const A
.
class A{}; // User type
template<typename T> void show(T a) {}
template void show<int>(int);
template void show<double>(double);
template<> void show<const A &>(const A& a){}
To run the example, save this code in a header file named
overload.hpp
, then generate a MATLAB interface named liboverload
following the instructions in
Header-Only HPP File.
Library Artifacts | MATLAB Interface libname | MATLAB Help |
---|---|---|
Header file |
|
|
Unique Function Names
The C++ interface generates unique function names based on the signature types. To view
the unique names for the show
function, type:
help clib.liboverload
Classes contained in clib.liboverload: A - clib.liboverload.A Representation of C++ class A. Functions contained in clib.liboverload: show - clib.liboverload.show Representation of C++ function show. show_AConst__ - clib.liboverload.show Representation of C++ function show. show - clib.liboverload.show Representation of C++ function show. show_double_ - clib.liboverload.show Representation of C++ function show. show - clib.liboverload.show Representation of C++ function show. show_int_ - clib.liboverload.show Representation of C++ function show.
To call the type-specific function for input of type double
,
type:
clib.liboverload.show_double_(var)
You can modify these names when publishing an interface to the library. For more information, see Customize Function Template Names.