简体   繁体   English

成员函数指针和模板的继承

[英]Inheritance with Member Function Pointers and Templates

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: 以及带有函数指针的模板化函数,然后针对B的列表对其进行调用:

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..." 如果我尝试调用getFunc(B::funA)收到“不存在getFunc(A :: funA)...”的编译错误。

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. 我可以通过简单地创建另一个getFunc A::func*而不是B ::的getFunc来解决问题,但是现在我有两个函数完全相同。 Is there a way for me to only end up with one implementation of getFunc ? 有没有办法让我只得到getFunc一个实现?

EDIT: I need a pre C++11 solution. 编辑:我需要一个预C ++ 11解决方案。

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 . std::result_of_t是C ++ 14,对于C ++ 11兼容的解决方案,请使用typename std::result_of<F(B&)>::type

For a C++03 solution, simply deduce the class type: 对于C ++ 03解决方案,只需推断类类型:

template <typename T, typename C>
std::vector<T> getFunc(T (C::*func)());

&B::funA has type bool (A::*)() , not bool (B::*)() . &B::funA类型为bool (A::*)() ,而不是bool (B::*)() You will need to perform a static_cast : static_cast<bool (B::*)()>(&B::funA) . 您将需要执行static_caststatic_cast<bool (B::*)()>(&B::funA)

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

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