什么是C++的模板元(Template Argument)?请提供一个示例。
在 C++ 中,模板参数(Template Argument)是指在模板的实例化过程中,为模板提供的具体类型、值或模板的参数。模板参数可以是类型、非类型或模板本身。
下面是一个示例,展示了如何使用模板参数来创建一个简单的类模板:
#include <iostream>// 定义一个类模板
template <typename T>
class MyContainer {
private:T element;public:MyContainer(T arg) : element(arg) {}T getElement() const {return element;}
};int main() {// 使用模板参数 int 实例化 MyContainer 类模板MyContainer<int> intContainer(123);std::cout << "Element in intContainer: " << intContainer.getElement() << std::endl;// 使用模板参数 double 实例化 MyContainer 类模板MyContainer<double> doubleContainer(3.14);std::cout << "Element in doubleContainer: " << doubleContainer.getElement() << std::endl;return 0;
}
在上面的示例中,MyContainer 是一个类模板,它有一个模板参数 T。在 main() 函数中,我们分别使用 int 和 double 类型实例化了 MyContainer 类模板,这两次实例化分别创建了 intContainer 和 doubleContainer 两个对象。在这里,int 和 double 就是模板参数。
当模板参数不是类型而是常量表达式时,我们可以创建一个模板类,其中的某些属性或行为在编译时就确定下来了。这样的模板称为模板元编程。以下是一个示例:
#include <iostream>// 模板类,其模板参数是一个整数常量表达式
template <int N>
class Factorial {
public:static const int value = N * Factorial<N - 1>::value;
};// 针对模板参数为 0 的特化版本
template <>
class Factorial<0> {
public:static const int value = 1;
};int main() {// 使用模板参数为 5 实例化 Factorial 模板类std::cout << "Factorial of 5 is: " << Factorial<5>::value << std::endl;// 使用模板参数为 10 实例化 Factorial 模板类std::cout << "Factorial of 10 is: " << Factorial<10>::value << std::endl;return 0;
}
在这个示例中,Factorial 是一个模板类,它的模板参数是一个整数常量表达式 N。通过递归定义,Factorial 类根据模板参数计算了 N 的阶乘。当 N 为 0 时,使用模板特化将递归终止,返回 1。在 main() 函数中,我们分别实例化了 Factorial<5> 和 Factorial<10>,得到了对应的阶乘值。