这种模板机制叫什么,它有什么用

What is this kind of template mechanism called and how is it useful?

本文关键字:什么 机制      更新时间:2023-10-16

这利用了多态函数的模板,但是什么时候有机会指定U模板类型呢?我不明白到底发生了什么。

除了解释之外,我还想要一个答案,其中还包括一个适用的用例。

下面是模板示例:

template<typename T>
class some_class
{
public:
   some_class(const some_class<T>& other) {
   }
   template<typename U>
   some_class(const some_class<U>& other) {
   }
};

标准库智能指针就是很好的例子。

(简体)

template <class T>
class unique_ptr
{
public:
    template <class U>
    unique_ptr(unique_ptr<U>&& u);
};

这允许将派生类型(U)的unique_ptr移动到基类型(T)的unique_ptr中。

函数模板参数可以自动推导,因此无需指定 U 的类型。

你可以写:

some_class<float> x(some_class<int>{});

您将被自动推断为类型 int .

一个用例

  some_class<int> x;       // assuming there is a suitable default constructor
  some_class<float> y(x);

当然,通常期望构造函数(模板化或非模板化)会以一种允许此类操作有意义的方式做一些有用的事情。

这是一个简单的转换构造函数,与模板没有任何关系。它允许将不同的类型转换为当前类型。这在智能指针中很常见,其中派生类的转换可以隐式转换为基类。

#include <iostream>
#include <memory>
template<typename T>
class Base
{
};
template<typename T>
class Derived : public Base<T>
{
};
template<typename T>
std::unique_ptr<Derived<T>> createDerived()
{
    return std::make_unique<Derived<T>>();
}
int main()
{
    std::unique_ptr<Base<int>> base = createDerived<int>();
    return 0;
}

在上面的示例代码中,由于转换构造函数,std::unique_ptr<Derived<int>>类型自动转换为std::unique_ptr<Base<int>。智能指针尝试尽可能接近地模拟原始指针,这是一个非常有用的属性。


std::unique_ptr文档显示有一个允许此转换的构造函数。

(六)

template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u );