#include
#include
template
class Box {
public:
void add(const T &t1) { t = t1; }
T get() const { return t; }
template
void inspect(const U &u) const {
::std::cout << "T: " << typeid(t).name() << "\n";
::std::cout << "U: " << typeid(u).name() << "\n";
}
private:
T t;
};
int main(int argc, const char *argv[])
{
Box integerBox;
integerBox.add(10);
integerBox.inspect(10);
return 0;
}
这是一个粗略的翻译。我取得了一些许可证,因为您必须使用引用/指针来引用java中的任何对象,C++中您可以将其直接放在那里。但基本上就是这样。
如果你想进一步弄糊涂,你可以把这个
main
:
#include // You could put this line at the top of the file,
// but it doesn't have to be there.
int main(int argc, const char *argv[])
{
Box integerBox;
Box< ::std::string > stringBox;
integerBox.add(10);
integerBox.inspect(10);
stringBox.add("Hello World!");
stringBox.inspect("Hello World!");
return 0;
}
我想你会发现
stringBox.inspect("Hello World!");