您的位置:首页 > 编程语言 > C语言/C++

C++ 类模板中非类型参数的模板参数

2015-03-28 11:06 267 查看
16.4.2. Template Arguments for Nontype Parameters

Now that we've seen more about how class templates are implemented, we can look at nontype parameters for class templates. We'll do so by defining a new version of the Screenclass first introduced
in Chapter 12. In this case, we'll redefine Screento be a template, parameterized by its height and width:

template <int hi, int wid>

class Screen {

public:

// template nontype parameters used to initialize data members

Screen(): screen(hi * wid, '#'), cursor (0),

height(hi), width(wid) { }

// ...

private:

std::string screen;

std::string::size_type cursor;

std::string::size_type height, width;

};

This template has two parameters, both of which are nontype parameters. When users define Screenobjects, they must provide a constant expression to use for each of these parameters. The class uses these parameters in the default constructor to set the size
of the default Screen.

As with any class template, the parameter values must be explicitly stated whenever we use the Screentype:

Screen<24,80> hp2621; // screen 24 lines by 80 characters

The object hp2621uses the template instantiation Screen<24, 80>. The template argument for hi is 24, and the argument for widis 80. In both cases, the template argument is a constant expression.

Note: Nontype template arguments must be compile-time constant expressions.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐