C++ 这种模板机制叫什么?它有什么用处?

C++ 这种模板机制叫什么?它有什么用处?,c++,templates,C++,Templates,这使得多态函数使用模板,但何时有机会指定U模板类型?我不明白到底发生了什么 除了解释之外,我想要一个答案,其中还包括一个适用的用例 以下是模板示例: template<typename T> class some_class { public: some_class(const some_class<T>& other) { } template<typename U> some_class(const some_class&

这使得多态函数使用模板,但何时有机会指定
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) {
   }
};
模板
上课
{
公众:
一些类(const一些类和其他){
}
模板
一些类(const一些类和其他){
}
};
用例

  some_class<int> x;       // assuming there is a suitable default constructor
  some_class<float> y(x);
某些_类x;//假设有一个合适的默认构造函数
部分y(x)类;
当然,通常会期望构造函数(模板化的或非模板化的)做一些有用的事情,以使这些操作有意义。

用例

  some_class<int> x;       // assuming there is a suitable default constructor
  some_class<float> y(x);
某些_类x;//假设有一个合适的默认构造函数
部分y(x)类;

当然,通常会期望构造函数(模板化或非模板化)会做一些有用的事情,以使这些操作有意义。

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

(简体)

模板
类唯一\u ptr
{
公众:
模板
唯一的(唯一的);
};

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

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

(简体)

模板
类唯一\u ptr
{
公众:
模板
唯一的(唯一的);
};

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

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

#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;
}

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

#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;
}

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

你可以写:

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

U将自动推断为类型
int

功能模板参数可以自动推断,因此无需指定U的类型

你可以写:

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

而U将自动推断为类型
int

,这难道不会使
x
成为类型
的某类
,而
构造函数只会接受
某类
?它看起来更像是一种支持构造函数中的
某些类
专门化的方法,这些专门化不属于“外部”
某些类
实例的模板类型。那么,你的答案中是否缺少
int
<代码>某个类y(x)我想OP是在问转换构造函数。@J。。函数模板参数可以自动推导。从
some_class
some_class
的转换将使用模板化构造函数(实例化)。我的答案中没有
int
遗漏。这难道不会使
x
类型的
成为某些类的
,而
构造函数只接受
某些类的
吗?它看起来更像是一种支持构造函数中的
某些类
专门化的方法,这些专门化不属于“外部”
某些类
实例的模板类型。那么,你的答案中是否缺少
int
<代码>某个类y(x)
我想OP是在问转换构造函数。@J。。函数模板参数可以自动推导。从
some_class
some_class
的转换将使用模板化构造函数(实例化)。我的答案中没有
int
遗漏。@VaughnCato答案的演示@VaughnCato答案的演示您刚刚声明了一个名为x的函数(这是C++最烦人的解析)。@JamesHopkin:Doh!有时它甚至让我很恼火。你刚刚声明了一个名为x的函数(这是C++最恼人的解析)。@JamesHopkin:Doh!它有时甚至让我感到烦恼。