在课程 10.7 -- typedef 与类型别名, 中,我们讨论了类型别名如何为现有类型定义别名。
为已明确指定全部模板参数的类模板创建类型别名,与创建普通类型别名完全相同:
#include <iostream>
template <typename T>
struct Pair
{
T first{};
T second{};
};
template <typename T>
void print(const Pair<T>& p)
{
std::cout << p.first << ' ' << p.second << '\n';
}
int main()
{
using Point = Pair<int>; // create normal type alias
Point p { 1, 2 }; // compiler replaces this with Pair<int>
print(p);
return 0;
}
这类别名既可以局部定义(例如在函数内部),也可以全局定义。
别名模板
有时我们希望为模板类创建类型别名,但不在别名中指定全部模板参数(而是由类型别名的使用者提供)。为此,可以定义别名模板,它是一种可用于实例化类型别名的模板。 与类型别名不会定义独立类型一样,别名模板也不会定义独立类型。
下面是一个示例:
#include <iostream>
template <typename T>
struct Pair
{
T first{};
T second{};
};
// Here's our alias template
// 别名模板 must be defined in global scope
template <typename T>
using Coord = Pair<T>; // Coord is an alias for Pair<T>
// Our print function template needs to know that Coord's template parameter T is a type template parameter
template <typename T>
void print(const Coord<T>& c)
{
std::cout << c.first << ' ' << c.second << '\n';
}
int main()
{
Coord<int> p1 { 1, 2 }; // Pre C++-20: We must explicitly specify all type template argument
Coord p2 { 1, 2 }; // 在 C++20 中,如果 CTAD 适用,可以使用别名模板推导来推导模板实参
std::cout << p1.first << ' ' << p1.second << '\n';
print(p2);
return 0;
}
在这个示例中,我们定义了名为 Coord 的别名模板,将其作为 Pair<T> 的别名,其中类型模板参数 T 由 Coord 的使用者提供。Coord 是别名模板,Coord<T> 是 Pair<T> 的实例化类型别名。定义后,可以在需要 Pair 的地方使用 Coord,在需要 Pair<T> 的地方使用 Coord<T>。
这个例子有几点值得注意。
第一,普通类型别名可以在代码块内定义,而别名模板必须在全局作用域定义(所有模板都如此)。
第二,在 C++20 之前,使用别名模板实例化对象时必须显式指定模板参数。 从 C++20 开始,可以使用别名模板推导:当别名所指向的类型支持 CTAD 时,它会根据初始化器推导模板参数的类型。
第三,由于 CTAD 不适用于函数参数,把别名模板用作函数参数时,必须显式定义别名模板使用的模板参数。 换句话说,应这样写:
template <typename T>
void print(const Coord<T>& c)
{
std::cout << c.first << ' ' << c.second << '\n';
}
而不是这样写:
void print(const Coord& c) // won't work, missing template arguments
{
std::cout << c.first << ' ' << c.second << '\n';
}
这与使用 Pair 或 Pair<T> 而不是 Coord 或 Coord<T> 没有区别。