I am trying to make a type alias for a function (myFunction) inside myClass.
template<typename T>
using calc_t = matrix<T> (MyClass<T>::*myFunction)(const matrix<T> &X);
Where I would get a generic syntax error, missing ')' before MyClass<T>::*myFunction
.
And then using it as so
calc_t<double> fptr = &MyClass<double>::myFunction;
I am not sure on the syntax to use in this specific case for when using the using
type alias as opposed to a non-templated typedef.
I have looked at the following other SO questions that don't seem to cover this specific usage:
I have tried some other variants but to no success.
As an alternative, and as I already suggested in a comment, you could use std::function
as it will be easier to use and more generic.
template <typename T>
class matrix { };
template <typename T>
class MyClass
{
public:
matrix<T> myFunction(matrix<T> const&) { return {}; }
};
template<typename T>
using calc_t = std::function<matrix<T>(matrix<T> const&)>;
int main()
{
MyClass<double> myObject;
using namespace std::placeholders; // For e.g. _1
calc_t<double> myFunction = std::bind(&MyClass<double>::myFunction, myObject, _1);
matrix<double> myFirstMatrix, mySecondMatrix;
myFirstMatrix = myFunction(mySecondMatrix);
}
As shown above, you could use std::bind
. But you could also use lambda expressions:
calc_t<double> myFunction = [&](matrix<double> const& m)
{
return myObject.myFunction(m);
};
Or better yet (for this simple use-case anyway) use type-deduction
auto myFunction = [&](matrix<double> const& m)
{
return myObject.myFunction(m);
};
With lambdas, type-deduction and templates you can create very generic and expressive and complex code in a simple way.