c++模板问题
我有一个类,它有一个用于其他目的的模板:
template<class t>
class MyClass {
public: //of course public...
t foo;
std::string text;
}
我有另一个类,它的方法通过参数获取所有这些类,并希望将指针存储在数组中。该类不想访问类的特定(临时)部分,而只想访问公共属性/方法。
class Container {
public: //of course public...
MyClass* array; //this is allocated with some magic.
void bar(MyClass& m) {
and want to store the class in a MyClass* array.
}
}
这是模板参数列表缺失的错误,
我该如何解决这个问题?
i have a class which has a template by other purposes:
template<class t>
class MyClass {
public: //of course public...
t foo;
std::string text;
}
and i have another class which method get all kind of these class through the arguments, and want to store the pointer in an array. The class dont want to access the specific (tempalted) parts of the classes only the common attributes/methods.
class Container {
public: //of course public...
MyClass* array; //this is allocated with some magic.
void bar(MyClass& m) {
and want to store the class in a MyClass* array.
}
}
here is the error that argument list for template missing
how can i solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法是使该函数也成为模板:
请注意,它可能应该是 const MyClass&,因为您不需要修改它。
你的新代码毫无意义。不存在
MyClass
类型的对象,因为MyClass
是一个模板。如果您想对这些类进行操作而不考虑它们的模板参数,那么您需要将非模板部分分解为基类:然后您可以引用该基类,并且当您调用虚拟函数时,它将动态分派:
The simplest method would be to make that function a template as well:
Note that that should probably be
const MyClass<t>&
, because you don't need to modify it.Your new code is meaningless. There is no such that as an object of type
MyClass
, becauseMyClass
is a template. If you want to operate on these classes irrespective of their template argument, then you need to factor out the non-template portions as a base class:Then you can refer to that base, and when you call a virtual function it will dynamically dispatch:
放置一个公共基类怎么样?
How about putting a common base class.
如果要创建“多模板”数组,最好使用非模板类作为模板类的基类。或者您可以创建一个模板数组并在其中存储任何对象。
If you want to create a "multi-template" array, you'd better use a non-template class as a base class of a template class. Or you can make a template array and store any objects in it.
类中的文本变量是私有的,因此除非您的 bar 函数是该类的方法,否则您不能像这样合法地使用它
the text variable in your class is private so unless you bar function is a method of the class you can't legally use it like that