非类型模板参数
我了解到:
- 非类型模板参数带有一些限制。一般来说,它们可能是常量整数值(包括枚举)或指向具有外部链接的对象的指针。
因此我编写了以下代码
1。
template <char const* name>
class MyClass {
…
};
char const* s = "hello";
MyClass<s> x; // ERROR:
此代码不起作用并产生错误's' 不是有效的模板参数
我的第二个代码也不起作用
2.
template <char const* name>
class MyClass {
…
};
extern char const *s = "hello";
MyClass<s> x; //error 's' is not a valid template argument`
但奇怪的是,这个代码很好
3.
template <char const* name>
class MyClass {
…
};
extern char const s[] = "hello";
MyClass<s> x; // OK
请告诉我什么是这三个代码都发生了?
还告诉我们如何纠正错误以使其他两个代码也能正常工作。
I have learned that:
- Nontype template parameters carry some restrictions. In general, they may be constant integral values (including enumerations) or pointers to objects with external linkage.
So i made following code
1.
template <char const* name>
class MyClass {
…
};
char const* s = "hello";
MyClass<s> x; // ERROR:
This code didn't work and produce error 's' is not a valid template argument
My second code also didn't work
2.
template <char const* name>
class MyClass {
…
};
extern char const *s = "hello";
MyClass<s> x; //error 's' is not a valid template argument`
But strangely this code is fine
3.
template <char const* name>
class MyClass {
…
};
extern char const s[] = "hello";
MyClass<s> x; // OK
please tell what is happening in all of these three codes??
also tell how to correct errors to make other two codes working also.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 此处:“模板参数列表中提供的非类型模板参数是一个表达式,其值可以在编译时确定时间”。
你会遇到一个问题,因为你的 char 指针在前两个示例中并不是真正恒定的。看看这个简短的例子:
这会给你
From here: "Non-type template argument provided within a template argument list is an expression whose value can be determined at compile time".
You get a problem because your char pointer is not really constant in the first two examples. Have a look at this short example:
Which will give you
我认为问题就在这里:
甚至
const char * const p="hello";
仅定义一个指针变量来存储内存的地址,编译时无法确定内存的值。
但
const char pp[]="你好";
编译器在编译时会知道内存是“hello”,而不是指向其他地方的指针。
这就是为什么
printf(" p=%p, &p=%p\n", p, &p);
将得到相同的值。
但是
printf("pp=%p, &pp=%p\n", pp, &pp);
不会显示相同的值。
I think the problem is here:
even
const char * const p="hello";
only define a pointer variable which stores the address of a memory, the value of the memory cannot be determined when compilation.
but
const char pp[]="hello";
the compiler will know when compile the memory is "hello", not a pointer to somewhere else.
that's why
printf(" p=%p, &p=%p\n", p, &p);
will get the same value.
but
printf("pp=%p, &pp=%p\n", pp, &pp);
will not show the same value.