指向类模板成员的函数指针

编程入门 行业动态 更新时间:2024-10-25 04:25:47
本文介绍了指向类模板成员的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我上了这堂课:

template <class T> class list { ... bool moreThan(T x, T y); bool lessThan(T x, T y); ... };

我需要一个函数指针来更改类的行为,并在使用bool moreThan(T, T)或bool lessThan(T, T)之间进行切换. 所以我目前正在使用:

I need a function pointer to change the behavior of my class, and switch between using bool moreThan(T, T) or bool lessThan(T, T). So I'm currently using:

bool (list<int>::*foo)(int x, int y); foo = &list<int>::lessThan;

并使用它:

(this->*foo)(x, y);

,但是我想有一个灵活的函数指针,这样我就可以将其与我需要的任何T一起使用,而不仅仅是int.那么有没有办法创建指向类模板成员的函数指针呢?像这样:

but I would like to have a flexible function pointer, so that I can use it with whichever T I need, not just int. So is there a way to create a function pointer to a class template member? Something like:

template <class T> bool (list<T>::*foo)(T x, T y); //this doesn't work

推荐答案

没有.指向成员的指针必须指向某物.类模板中的成员函数不是单个函数,而是一系列函数-每个函数都有不同的类型.甚至可能存在T,而list<T>::lessThan并不存在,或者是类型还是变量!

No there isn't. A pointer-to-member has to point to something. A member function in a class template isn't a single function, it's a family of functions - and each one has a different type. There could even be a T for which list<T>::lessThan doesn't exist, or is a type or a variable!

如果我们为这样一个指向成员的指针做了别名:

If we made an alias for one such pointer to member:

template <typename T> using CompFun = bool (list<T>::*)(T, T);

然后很明显CompFun<int>和CompFun<string>是不同的类型.您不能创建通用的CompFun<T>变量.

Then it's obvious that CompFun<int> and CompFun<string> are different types. You cannot create a generic CompFun<T> variable.

但是,根据您要尝试执行的操作,可能有一种很好的方法来完成该操作.

Depending on what it is you're trying to do, though, there might be a good way to accomplish that.

更多推荐

指向类模板成员的函数指针

本文发布于:2023-07-28 02:42:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226556.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   函数   模板   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!