I have two classes:
class A {
public:
bool funA();
};
class B : public A {
pubic:
bool funB();
};
and a templated function that takes a function pointer and then calls it against a list of B's:
template <typename T>
std::vector<T> getFunc(T (B::func*)()) {
....iterator through list of B's calling func....
}
If I try to call getFunc(B::funA)
I get a compile error that "no getFunc(A::funA) exists..."
I can solve the problem by simply creating a second getFunc
that takes A::func*
instead of B::, but now I have two functions doing the exact same thing. Is there a way for me to only end up with one implementation of getFunc
?
EDIT: I need a pre C++11 solution.
Simply deduce the entire parameter and extract its return type:
template<class F,class R=std::result_of_t<F(B&)>>
std::vector<R> getFunc(F&&){return{};}
std::result_of_t
is C++14, for a C++11 compatible solution, use typename std::result_of<F(B&)>::type
.
For a C++03 solution, simply deduce the class type:
template <typename T, typename C>
std::vector<T> getFunc(T (C::*func)());
&B::funA
has type bool (A::*)()
, not bool (B::*)()
. You will need to perform a static_cast
: static_cast<bool (B::*)()>(&B::funA)
.
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.