Template typename

Template typename

本文关键字:typename Template      更新时间:2023-10-16

C++ standard是否在以下声明中以某种方式指定了T可以是什么?

template <typename T>

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

但是的严格定义呢?

按照您的要求,如下:

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
..

类型形参将其标识符定义为模板声明范围内的类型名称(如果用class或typename声明)或模板名称(如果用template声明)。

.

如果在模板专门化的实例化中使用模板实参导致了不良形式的构造,则该程序是不良形式的。

其他部分用于默认参数、非类型模板等。换句话说,该标准没有关于T的任何内容。

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

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

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

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