- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
早上好
我有一个模板化类,我想通过指针 vector 来操作对象。要使用指向模板化类的指针 vector ,我需要从非模板化类派生此类,我做到了。
这是我的问题:要从指向基类的指针调用派生类的方法,我不能使用虚函数,因为不能将模板函数设为虚函数。我需要进行显式转换,这很乏味:一旦使用 new 创建数字对象,实际上需要向下转换为 number*,尽管该对象事先已知为数字。
我以一种笨拙的方式解决了这个问题:函数 myset 测试所有支持的 typeid 值以获得正确的动态转换。它是执行 typeid 检查的一长串嵌套 ifs。
除了繁琐之外,该函数仅适用于调用'set'方法,并且应定义类似的函数以调用其他方法。如果我可以对我指向的对象类型进行自动转换,一切都会简单得多。
该方法的缺点是:
编译器知道 lst[0](在下面的代码中)指向一个数字对象,尽管 lst 是一个元素对象的 vector ,从中派生出 number<> 个对象。
是否有一种方法可以自动将定义为 base* 的指针向下转换为指向实际指向的对象的指针?
如果我有正确的向下转换,那么我可以在 number<> 类中定义数千个方法并使用正确转换 -> function(...) 调用调用它们
代码如下(可以正常运行,核心是“myset”的定义)
提前致谢,彼得罗 M.
PS 我最感兴趣的是标准 C++ 方法,而不使用除 STL 之外的其他库,例如 Boost。
#include <iostream>
#include <vector>
#include <typeinfo>
using namespace std;
class element
{
public:
virtual void print() = 0; // print is not templatized and works properly
//template <class T> virtual set(T v) = 0; // this would solve all my problems, if only it were legal.
};
template <class T>
class number : public element
{
T val;
public:
void print() {cout << "number is " << val << endl;}
void set(T v) {val = v;}
};
// That's the best I can do!
template <class T>
void myset(T v, element *ptr)
{
// There is a kink in the template: the compiler checks the T type by the value of v, that in this case is an integer:
// cout << "Type name for the template is: " << typeid(T).name() << endl;
// cout << "Type name for an integer is: " << typeid(int).name() << endl;
if (typeid(*ptr) == typeid(number<double>))
{
((number<double> *) ptr) -> set(7);
return;
}
else if (typeid(*ptr) == typeid(number<float>))
{
((number<float> *) ptr) -> set(7);
return;
}
// add other types... (tedious)
else
{
cout << "type not supported" << endl;
}
}
int main()
{
vector <element *> lst; // list of heterogeneous templatized objects
lst.push_back(new number<float>);
lst.push_back(new number<double>);
lst[0] -> print();
//((number<float> *) lst[0]) -> set(7); it's correct but it requires I know the type when I call it (tedious)
myset(7, lst[0]); // may be inefficient, but it works (for the types which are explicitly supported)
// cast_to_what_the_pointer_actually_points_to <lst[0]> -> set(7); // that's what I'd like to do: a downcast function which checks the object type and returns the correct pointer would be able to call any class method...
lst[0] -> print();
}
最佳答案
你快到了。您需要有一个模板化的 set
方法,该方法使用 typeid
和指向其参数的 void *
指针调用私有(private)虚方法,从而允许覆盖决定如何处理它:
class element
{
virtual void set_impl(const std::type_info &, const void *) = 0;
public:
template <class T> void set(T v) { set_impl(typeid(v), &v); }
};
以及如何编写 set_impl
的示例:
template <class T>
class number : public element
{
T val;
void set_impl(const std::type_info &ti, const void *pv) {
if (ti == typeid(T)) {
val = *static_cast<const T *>(pv);
} else {
throw std::invalid_argument("incorrect type to set()");
}
}
};
这类似于 Boost.Any 采取的方法.
关于c++ - 自动向下转换指向派生对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784783/
我有一个无法理解的奇怪编译问题。 //I know, you should never derive from the STL Library template class SharedClass :
我是一个刚开始学习 Haskell 的菜鸟,所以如果我问愚蠢的问题,请耐心等待。 最近我在 SO 中遇到了演示如何导出函数和表达式的类型和实现的问题(诸如 How can I understand "
如何自动派生此 GADT 的 Read 实例: {-# LANGUAGE GADTs, StandaloneDeriving #-} data TypeDec a where TypeDecInt
我遇到了我想要的情况 Deal class要注意它DealDetail type反之亦然,我想 DealDetail注意Deal type .将来我想有很多 Deal 的后代和 DealDetails
我是 C# 新手,所以请多多包涵。 好的,所以我在不同的程序集中有两个类需要相互引用: namespace AssemblyA { class A { private B MyB {
简而言之,我已经实现了一个派生自 SynchronizationContext 的类,以便 GUI 应用程序可以轻松地使用在 GUI 线程以外的线程上引发的事件。我非常感谢对我的实现的评论。具体来说,
我正在设计一个小型系统,想知道如何为派生类分配内存的细微差别。 如果我有两个类(class) class foo { public: int a; Foo(): a(0) {}; }; class
我正在尝试编写一个派生 PartialEq 的枚举,其中包含一个手动执行此操作的特征对象。我使用了解决方案 here为了强制 Trait 的实现者编写相等方法。这无法编译: trait Trait {
以下代码可以编译(特别是 MyError 被识别为具有调试特性): use std::str; use std::fmt; #[derive(Debug)] enum MyError where F:
是否有一种简单的方法来注释结构中的字段,以便在派生 PartialEq 特征时忽略它们?例如: #[derive(PartialEq,Eq)] pub struct UndirectedGraph {
我正在编写代码来处理“Foo”类型的对象。 foo 是一种容器,为了提供对其元素的高效和抽象访问,它提供了 Element 类型的嵌套类。 Element 包装对象在容器中的位置。 现在,“Foo”可
假设如下: class child : public parent { public: fun1(parent * obj); //somewhere on the child class
我有几个模板类 template class Transition { public: virtual Cost getCost() = 0; }; template class St
我正在尝试使用自定义 QSortFilterProxyModel . 这是我的标题: #include class QSortFilterProxyModel_NumbersLast : publi
我正在使用 C# 和 mvc3。我在解决方案中添加了一个项目。我想创建一个新 Controller 并让它从我添加的项目中的 Controller 派生。我该怎么做? 最佳答案 在 Visual St
我在 python 中有一个对象,它派生自 QtGui.QGraphicsPixmapItem,具有一些基本属性和方法。在对此对象的引用上调用 deepcopy 后,当我尝试使用该副本时收到一条错误消
由于只能给FixedDocument添加页面,所以我写了一个派生类: public class CustomFixedDocument : FixedDocument { public voi
我在自定义 QMainWindow 时遇到了很大的问题,因为我不知道如何实现以下内容: 在 QMainWindow 文档中,QMainWindow 有一些用于工具栏、停靠小部件、状态栏和其他的特殊区域
我想感受一下QT,决定写一个小的十六进制编辑器。为此,我需要一个允许滚动的小部件。经过一番研究,我发现 QTextEdit 为此目的派生自 QAbstractScrollArea。在阅读 QAbstr
我正在寻找一种可以从已经发生的洗牌过程中派生出 key 的算法。 假设我们有被打乱的字符串“Hello”: "hello" -> "loelh" 现在我想从中导出一个 key k,我可以用它来撤销洗牌
我是一名优秀的程序员,十分优秀!