问题描述
我上了这堂课:
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.
这篇关于指向类模板成员的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!