BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #35379同步于 2010/1/22
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

问两个问题:类型检查和无类型模板参数

disk
2010/1/22镜像同步5 回复
1.见到C++教材里多次鼓吹“C++会执行严格的类型检查”,请问类型检查到底指什么,难道C没有严格的类型检查吗? 2.下面的程序怎么解释 template<typename T, void* ptr> class A {}; char str[10]; int main() { A<double, str> a;//ok return 0; } template<typename T, void* ptr> class A {}; int main() { char str[10]; A<double, str> a;//error return 0; } error C2971: a local variable cannot be used as a non-type argument 查阅了MSDN的文档: Non-type template parameters must be of integral, enumeration, pointer, reference,or pointer to member type, and must be constant at compile time. 请问一下上面的错误和文档中的描述有什么不一致吗?为什么会出错呢?谢谢!
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
allen0308机器人#1 · 2010/1/22
1、c风格的转换可以在任意类型间进行,而c++对于不同的功能有不同的转换方式,若出错则会throw异常 2、类模板的非类型模板实参必须是编译时的常量。第一个str是,而第二个在栈里 【 在 disk 的大作中提到: 】 : 1.见到C++教材里多次鼓吹“C++会执行严格的类型检查”,请问类型检查到底指什么,难道C没有严格的类型检查吗? : 2.下面的程序怎么解释 : template<typename T, void* ptr> : ...................
Jarod机器人#2 · 2010/1/22
char * != void *吧。。。 【 在 allen0308 的大作中提到: 】 : 1、c风格的转换可以在任意类型间进行,而c++对于不同的功能有不同的转换方式,若出错则会throw异常 : 2、类模板的非类型模板实参必须是编译时的常量。第一个str是,而第二个在栈里
jokerlee机器人#3 · 2010/1/22
【 在 Jarod 的大作中提到: 】 : char * != void *吧。。。 void* 是C99的胡泛型指针 c89里是char *
disk机器人#4 · 2010/1/24
能说一下为啥在栈里的就不是编译时常量呢?编译方面不太懂 【 在 allen0308 的大作中提到: 】 : 2、类模板的非类型模板实参必须是编译时的常量。第一个str是,而第二个在栈里
disk机器人#5 · 2010/1/24
解决了.《c++ templates》 Nontype template arguments are the values substituted for nontype parameters. Such a value must be one of the following things: - Another nontype template parameter that has the right type - A compile-time constant value of integer (or enumeration) type. This is acceptable only if the corresponding parameter has a type that matches that of the value, or a type to which the value can be implicitly converted (for example, a char can be provided for an int parameter). - The name of an external variable or function preceded by the built-in unary & ("address of") operator. For functions and array variables, & can be left out. Such template arguments match nontype parameters of a pointer type. - The previous kind of argument but without a leading & operator is a valid argument for a nontype parameter of reference type. - A pointer-to-member constant; in other words, an expression of the form &C::m where C is a class type and m is a nonstatic member(data or function). This matches nontype parameters of pointer-to-member type only.