模板参数必须是类型吗?

ubb*_*bdd 6 c++ templates

在Bjarne Stroustrup C++ Book(第13章,第331页)中,它说"模板参数可用于后续模板参数的定义".它提供了以下代码:

template<class T, T def_val> class Cont{ /* ... */ }
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供如何使用此模板的示例.例如,如何初始化Cont的对象?在我看来,"def_val"不是类型参数,不应该放在<>中.我错了吗?

非常感谢

小智 7

你可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

模板参数不需要是类型.

仅当工作T为一个整数类型(int,unsigned,long,char等,但不float,std::string,const char*,等),如@Riga在他/她的评论中提及.


Bjö*_*lex 6

def_val是一个值参数.实例化可能如下所示:

Cont<int, 1> foo;
Run Code Online (Sandbox Code Playgroud)

有用的一个有趣的例子是当你想要一个指向类成员的指针作为模板参数时:

template<class C, int C::*P>
void foo(C * instance);
Run Code Online (Sandbox Code Playgroud)

这使得能够foo使用指向int任何类的类型成员的指针来实例化.

  • 虽然我认为正确的术语是"非类型模板参数". (2认同)