gpt4 book ai didi

c++ - 模板类类型特定的函数

转载 作者:太空狗 更新时间:2023-10-29 20:35:52 24 4
gpt4 key购买 nike

好的,所以我有了这个模板类,它有点像单向列表。

template <typename T> List

它有这个内部函数打印

public:
void Print();

如您所料,它从头到尾打印列表内容;然而,由于模板可以将类作为 T,可以想象,对于这种情况,我将需要不同的 Print() 实现。比如我还有一个类Point

class Point{
private:
int x, y;
public:
int getX();
int getY();
}

所以我想要专门为 Points 设计的 Print。我试过这个:

void List<Point>::Print();

但是编译器告诉我

prototype for void List<Point> Print() doesn match any in class List<Point>

虽然

candidates are: from List<T> [with T = Point] void List<Point>::Print()

对我来说,这似乎是相同的功能。怎么了?以及如何编写特定于 T 的模板类函数?

最佳答案

您使用 explicit template specialization为特定类型专门化 Print 的行为。

例如,对于:

template <> // No template arguments here !
void List<Point>::Print() // explicitly name what type to specialize
{
//code for specific Point Print behaviour..
}

关于c++ - 模板类类型特定的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com