模板类型名称

时间:2011-11-20 20:49:00

标签: c++ templates types typename

C++ standard是否以某种方式指定了T在以下声明中的含义:

template <typename T>

我的意思是,从实际的角度来看,这可以是任何特定的类型,它允许模板编译(当相应的替换发生时)

严格定义呢?

4 个答案:

答案 0 :(得分:2)

正如您想要的标准,这里是:

C ++ 03,14.1,模板参数:

A template defines a family of classes or functions.

template-declaration:
    exportopt template < template-parameter-list > declaration
template-parameter-list:
    template-parameter
     template-parameter-list , template-parameter

template-parameter:
    type-parameter
    parameter-declaration
type-parameter:
    class identifieropt
    class identifieropt = type-id
    typename identifieropt
    typename identifieropt = type-id
    template < template-parameter-list > class identifieropt
    template < template-parameter-list > class identifieropt = id-expression

..
  

type-parameter将其标识符定义为模板声明范围内的type-name(如果使用class或typename声明)或template-name(如果使用模板声明)。

     

...

     

如果在模板专业化的实例化中使用template-argument会导致格式错误的构造,那么该程序就会形成错误。

其他内容适用于默认参数,非类型模板等。换句话说,标准不会说任何关于T

答案 1 :(得分:1)

程序员有责任确保用于T的数据类型兼容,并且具有将在T上执行的所有必要操作。就C ++标准而言,可以使用任何数据类型代替T

答案 2 :(得分:0)

没有严格的定义,因为这似乎违背了模板的目的。 T是任何类型,例如,作为参数传递给参数类型为T的函数。

您为模板的代码可重用性牺牲了严格类型定义的安全性。有了这种自由,您需要提供检查以确保T是该函数的合理类型。

答案 3 :(得分:0)

boost有一个有用的模板,enable_if,它允许您只为特定类型启用模板。

相关问题