在C++中,template<>被用来指定模板的特化,即针对特定类型的模板定义。
例如,我们可以使用template<>特化std::swap,以支持交换自定义类型的对象:
#include
#include
struct Foo {
int x;
};
namespace std {
template<>
void swap(Foo& lhs, Foo& rhs) noexcept {
using std::swap;
swap(lhs.x, rhs.x);
}
}
int main() {
Foo a{1}, b{2};
std::swap(a, b);
std::cout << "a.x=" << a.x << ", b.x=" << b.x << '\n';
}
在上面的示例中,我们特化了std::swap以支持自定义类型Foo的对象交换。通过使用template<>,我们定义了一个无符号整数的swap版本,它基于std::swap实现,但交换Foo的x成员而不是整个对象。
因此,我们可以看到C++的template<>具有非常强大的特性,可以用于高度定制化的用例。
下一篇:标准库异常抛出的消息是否已定义?