模板&LT; template <typename> something_else&gt;,这是什么?</typename>

时间:2014-03-16 20:38:54

标签: c++ templates template-templates

我刚刚开始学习C ++ 11,我从未在新功能列表中看到这种语法:

template <template <typename> class F>
struct fun;

它是什么以及它是如何运作的?

2 个答案:

答案 0 :(得分:3)

注意:你所看到的是一个&#34; old&#34;功能,并且早在c ++ 11之前就已存在。


template <template <typename> class F> struct Obj;

在上面Obj是一个只接受模板参数的模板,模板参数也是模板 [1] ;这通常被称为template-template parameter [2]

1)在这个具体的例子中,它只接受一个带有一个类型参数的模板。
2)链接到SO问题: Template Template Parameters


想象一下,您希望在某个类模板周围有一个包装器;只要您可以为它指定模板参数,就不必关心这个类模板。

如果是这样,您可以使用 template-template parameter ,如下例所示:

template<template<typename T> class TemplateType>
struct Obj {
  TemplateType<  int> m1;
  TemplateType<float> m2;
};

template<typename T>
struct SomeTemplate { /* ... */  };

Obj<SomeTemplate> foo;

在上文中,foo将是Obj<SomeTemplate>,其中包含两名成员:

  1. SomeTemplate< int> m1
  2. SomeTemplate<float> m2

答案 1 :(得分:2)

这也适用于C ++ 98。这是一个模板作为模板的参数。我的意思是模板类将作为F的参数。 也许这个页面可以帮助您:http://www.cprogramming.com/tutorial/templates.html

相关问题