什么是C ++的Java通配符? [英] What's a C++ equivalent of Java wildcards?
问题描述
在Java中,如果您有类似的类:
In Java if you have a class like:
class Box<E>
{
some code
}
您可以使用通配符执行以下操作:
you can do the following using a wildcard:
Box<?> someBox;
someBox = new Box<Integer>();
someBox = new Box<Double>();
有没有办法在C ++中做到这一点?
Is there a way to do this in C++?
用更好的话来说,我该如何在C ++中声明一个变量,该变量可以容纳 Box< Integer>
或 Box< Double>
或 Box< WhateverDataTypeHere>
?
In better words, how can I declare a variable in C++ that can hold either Box<Integer>
or Box<Double>
or Box<WhateverDataTypeHere>
?
推荐答案
template< typename T>Box类
应该从非模板基继承(例如 BasicBox类
类).
template <typename T> class Box
should inherit from a non-template base (let's say class BasicBox
).
然后指向 BasicBox
的指针可以指向派生模板的专业化对象:
Then a pointer to BasicBox
can point to objects of the specializations of the derived template:
BasicBox *someBox = new Box<int>;
或者,因为在现代C ++™中应该避免手动管理内存,所以使用智能指针将是一个更好的主意:
Or, since in modern C++™ manually managing memory should be avoided, using a smart pointer would be a better idea:
std::unique_ptr<BasicBox> someBox = std::make_unique<Box<int>>();
这篇关于什么是C ++的Java通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!