【发布时间】:2016-08-17 22:36:42
【问题描述】:
我正在尝试创建以下流程:
有一个“基础”类,没有参数或功能,这样我就可以持有 方法中的基指针。
它的派生类是一个模板,它在给定的模板参数对象类型上实现 operator()。
我正在尝试,通过使用指向基类的指针,在运行时调用派生类 operator()。
我已经尝试使用 CRTP 来实现它 (https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) 但是,当派生类是类模板时,这似乎不起作用。
这是我的代码:
class Base {};
template<typename Ref_Obj, typename Obj_Type>
class Derived : public Base {
private:
typedef bool (Ref_Obj::*Func_p)(Obj_Type) const;
Func_p m_func;
const Ref_Obj& m_db;
public:
Derived<Ref_Obj, Obj_Type>(const Ref_Obj& db, Func_p func): m_db(base), m_func(filter) {}
inline bool operator()(const Obj_Type& obj) const {
return (m_db.*m_func)(obj);
}
}
现在,用法是在另一个类模板中,它包含基类指针的向量,如下所示,并且有自己的 operator():
template<typename Obj_Type2> /* Upon usage, Obj_Type2 is the same as Obj_Type, this is just to differ the two in the code here */
class BlaBla {
private:
std::vector<const Base *> m_vec;
public:
/* relevant constructors ... */
inline bool operator()(const Obj_Type2 &obj) const {
for(std::vector<const Base *>::const_iterator it = m_vec.begin(); it != m_vec.end(); ++it) {
/*** This is the problematic line V ***/
if( (*it).operator()(obj) ) { /* DO SOMETHING */ }
}
}
当然,编译器抱怨在下面代码中标记的有问题的行中没有要调用的匹配函数,但我无法找到进行相关调用的方法。
第一个解决方案想到的是创建一个 virtual operator()(...),具有 特定的对象类型,例如Base 类中的 virtual operator()(const uint32_t &obj) 有效,但我的意图是 operator()(...) 将接收各种对象类型,并为每个对象声明一个虚拟方法不优雅,似乎打破了我想在这里实现的所有模板概念。
想到的第二个解决方案,以某种方式将 Ref_Obj 和 Obj_Type 类型名传递给基类,以用于某种接口方法,这将使用 static_cast 调用适当的 Derived 运算符(如在 CRTP 中) - 但这似乎不起作用,因为 Derived 类是类模板,而且 BlaBla 类也不直接知道 Ref_Obj类型名称。
有没有其他方法可以对 Deriver operator() 进行适当的调用
【问题讨论】:
-
您想要传递给派生
operator()的类型范围是什么?如果它们都有一些共同的祖先TypeBase,您可以声明protectedvirtual bool Base::operator()(TypeBase&)和publictemplate<T> bool Base::operator()(T&)以虚拟的形式实现,在派生类中被覆盖。 -
它们不共享一个共同的祖先,因为它们可以是类指针、原始类型等
标签: c++ templates inheritance template-specialization