简体   繁体   English

模板类函数指针类型别名

[英]Template class function pointer type alias

I am trying to make a type alias for a function (myFunction) inside myClass. 我正在尝试为myClass内的函数(myFunction)创建类型别名。

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 . 在哪里我会得到通用语法错误, 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. 我不知道在语法在这一特定的情况下,使用使用时using类型别名,而不是一个非模板的typedef。

I have looked at the following other SO questions that don't seem to cover this specific usage: 我看了以下其他SO问题,这些问题似乎并未涵盖此特定用法:

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 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. 作为替代,正如我在评论已经建议,你可以使用std::function ,因为它会更容易使用更通用。

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 . 如上所示,您可以使用std::bind But you could also use lambda expressions : 但是您也可以使用lambda表达式

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. 使用lambda,类型推导和模板,您可以以简单的方式创建非常通用,富有表现力的复杂代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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