nontypes模板参数

nontypes template parameter

本文关键字:参数 nontypes      更新时间:2023-10-16

我已经了解到:

  • 非类型模板参数有一些限制。通常,它们可以是常量整数值(包括枚举)或指向具有外部链接的对象的指针

所以我做了以下代码

1.

 template <char const* name> 
 class MyClass { 
    … 
 }; 
 char const* s = "hello";  
 MyClass<s> x;         // ERROR:

此代码不起作用,并产生错误's' is not a valid template argument

我的第二个代码也不起作用

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  

请告诉我这三个代码都发生了什么??

还告诉如何纠正错误,使其他两个代码也能工作。

从这里开始:"模板参数列表中提供的非类型模板参数是一个表达式,其值可以在编译时确定"。

您会遇到一个问题,因为在前两个示例中,您的char指针并不是真正的常量。看看这个简短的例子:

int main() {
        char const *c = "foor";
        std::cout << "c: " << c << std::endl;
        c = "bar";
        std::cout << "c: " << c << std::endl;
}

这会给你

c: foo
c: bar

我认为问题就在这里:甚至

const char*const p="你好";

只定义一个存储内存地址的指针变量,编译时无法确定内存的值。但是

const char pp[]="你好";

编译器在编译时会知道内存是"hello",而不是指向其他地方的指针。这就是的原因

printf("p=%p,&p=%p\n",p,amp;p);

将获得相同的值。但是

printf("pp=%p,&pp=%p\n",pp,&pp);

将不会显示相同的值。