使模板化成员函数实例化给定类类型的对象 [英] Make templated member function instantiate object of given class type

查看:40
本文介绍了使模板化成员函数实例化给定类类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类A和B.我希望A有一个模板化函数makeObject(),它生成给定类模板类型的新对象并将其存储在内部。


以下是正确的吗?

Say I have two classes A and B. I want A to have a templated function "makeObject()", which makes a new object of the given class template-type and stores it internally.

Is the below correct?

展开 | 选择 | Wrap | 行号

推荐答案

我修复了你的代码。将我所做的与原始代码进行比较。


在课堂定义之外调用它们时,不要忘记公开您的成员函数。



I fixed your code. Compare what I did to the original code.


Don''t forget to make your member functions public when calling them from outside the class definition.




展开 | 选择 | Wrap | 行号


不完全,但我很感激努力: - )


我认为你错过了内部存储的部分。问题是新对象不应该被发送出去,而是存储在里面。


我忘了提到的一件事:createObject函数的返回是新对象的id(或game-id)(所以返回0里面很好)。


主要区别在于模板类在代码中用作函数的返回类型,但不在我的代码中。
Not exactly, but I appreciate the effort :-)

I think you missed the part with "stores it internally". The thing is that the new object should not be sent out, but stored inside.

A thing I forgot to mention: the return of the createObject function is the id (or game-id) of the new object (so returning 0 inside is fine).

The main difference is that the template class is used as the return type of the function in you''re code, but not in my code.


createObject成员函数希望将创建的对象作为私有成员变量存储在其类中。这意味着类型为T的成员变量。这意味着模板类。


一种方法是在创建的对象上使用多态,这样类只需要存储一个基础类指针。


如果这不起作用,你可以设计一个包并将包放在类对象中,并使用包处理程序将创建的对象移入和移出。 />

你可能会看看微软和VARIANT。需要大量的类型转换,但易于使用。
The createObject member function would want to store the created object as a private member variable inside its class. That would mean a member variable of type T. That would mean a template class.

One way around that is to use polymorphism on the created objects so the class only needs to store a base class pointer.

If this doesn''t work you can design a bag and keep the bag in the class object and use a bag handler to move created objects in and out.

You might look at Microsoft and the VARIANT. Lots of typecasting required but easy to use.


这篇关于使模板化成员函数实例化给定类类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆