模板参数必须是类型
Must template parameters be types?
在Bjarne Stroustrup C++书(第13章,第331页(中,它说"一个模板参数可以用于后续模板参数的定义"。它给出了以下代码:
template<class T, T def_val> class Cont{ /* ... */ }
有人能提供一个如何使用这个模板的例子吗。例如,如何初始化Cont的对象?在我看来,"def_val"不是一个类型参数,不应该放在<>中。我错了吗?
非常感谢
您可以这样做:
Cont<int, 6> cnt;
// ^ as long as this is of type T (in this case int)
// def_val will be of type int and have a value of 6
模板参数不需要是类型。
只有当T
是积分类型(int
、unsigned
、long
、char
等,而不是float
、std::string
、const char*
等(时,这才有效,正如@Riga在其评论中提到的那样。
def_val
是一个值参数。实例化可能如下所示:
Cont<int, 1> foo;
当你想要一个指向类成员的指针作为模板参数时,这是有用的一个有趣的例子:
template<class C, int C::*P>
void foo(C * instance);
这使得foo
能够用指向任何类的int
类型的成员的指针来实例化。
下面是如何实例化上面的示例:
template<class T, T def_val> class Cont{ /* ... */ };
int main()
{
Cont<int,42> c;
}
T def_val
是类型为T
的对象(之前已传递(。例如,它可以用于初始化容器中的项。使用时,它看起来像:
Object init(0);
Cont<Object, init> cont;
(psuedo代码;Object
显然必须是以这种方式合法使用的类型(
然后使用第二个模板参数。它包含在模板中是因为它具有模板化的类型;def_val
的类型必须为T
,并且必须在创建对象时传递。
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法