这种模板机制叫什么,它有什么用
What is this kind of template mechanism called and how is it useful?
这利用了多态函数的模板,但是什么时候有机会指定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 );
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- C++20 中协程的机制是什么
- 使用C 17处理Unicode的有效,符合标准的机制是什么
- 带缓冲区的 iostream 的机制是什么?
- C++中"机械臂"的机制是什么?
- 与Java的InputMismatchException和IOException Handling等效的C++异常处理机制是什么
- QTimer对象是否在单独的线程中运行?它的机制是什么
- 这种模板机制叫什么,它有什么用
- 什么是Qt帧缓冲工作机制
- 什么编译机制铸造新运算符的结果
- QNetworkAccessManager中的并行机制是什么
- 多线程和多进程应用程序的锁定机制之间有什么区别
- 什么时候使用std::promise优于其他std::线程机制是一个好主意?
- 当我从赋值操作符返回值时,首先,调用复制构造函数的机制和基础是什么?