简体   繁体   中英

Template class function pointer type alias

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.

It looks like the issue is that you are trying to name the function pointer on the right side as well. The following compiled for me:

template <typename T>
class Matrix { };

template <typename T>
class MyClass
{
public:
    Matrix<T> myFunc() { return {}; }
};

template <typename T>
using my_f = Matrix<T> (MyClass<T>::*)(); // NOTE: No myFunction here

int main() {
    my_f<double> f = &MyClass<double>::myFunc;
    return 0;
}

https://www.ideone.com/VdazMB

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM