nontypes模板参数
nontypes template parameter
我已经了解到:
- 非类型模板参数有一些限制。通常,它们可以是常量整数值(包括枚举)或指向具有外部链接的对象的指针
所以我做了以下代码
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);
将不会显示相同的值。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- nontypes模板参数