C ++非类型模板参数const char * [英] C++ non-type template parameter const char*

查看:305
本文介绍了C ++非类型模板参数const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有

 模板< const char *> 
结构A {};

//静态存储
const char a [] = asd;
const char * p = asd;

此实例

  A&a; {}; 

可以编译。这是可以理解的-数组 a 衰减到指向第一个元素的指针。但是,如果我们用 p 实例化 A

  A< p> {}; 

编译器给出错误:


错误:类型为'char *'的非类型模板参数不是常量表达式


为什么不这样做? t标准允许指定类型为 const char * 的命名变量,或者仅指定字符串文字 asd ,即bvalue本身,作为模板参数?

解决方案

数组 a 是一个常量字符数组,在编译时已完全初始化,并且编译器还获得了已知的内存地址,这就是为什么它可以衰减到模板中的指针的原因。



但是 p 是指向常量字符数组的 pointer ,但是指针本身不是编译时常量,可以更改为指向其他字符串,并且在编译时未初始化,但在链接时(在编译后发生)或加载程序时未初始化编入内存。 p 的地址在编译时是已知的,但字符串文字 p 指向的地址不知道。 / p>




为了扩展在编译时不知道字符串文字地址的原因,这是因为将其放在一个由编译器代码生成器生成的特殊只读段,然后将该只读段与来自其他 翻译单元 。这就是为什么直到链接时(最早)才知道字符串文字的最终地址。


Let's say we have

template <const char*>
struct A{};

// static storage
const char a[] = "asd";
const char* p = "asd";

This instantiation

A<a>{};

is okay for compiler. And this is understandable - array a decays to pointer to first element. But if we instantiate A with p like this

A<p>{};

compiler gives an error:

error: non-type template argument of type 'char *' is not a constant expression

Why doesn't Standard allow to specify named variable of type const char* or just string literal "asd", which is btw lvalue itself, as a template argument?

解决方案

The array a is a constant array of character, it's fully initialized at the time of compilation and also gets a know memory address by the compiler which is why it can decay to a pointer in a template.

But p is a pointer to a constant array of characters, but the pointer itself is not a compile-time constant, and can be changed to point to other strings, and it's is not initialized at time of compilation but either on time of linking (which happens after compilation) or when the program is loaded into memory. The address of p is known at time of compilation, but not the address of the string literal p points to.


To expand on the reason the address of the string literal is not known at time of compilation, it's because it's put in a special read-only segment by the compilers code-generator, and that read-only segment is then combined with the read-only segments from the other translation units when linking. This is why the final address of the string literal can't be known until the time of linking (at earliest).

这篇关于C ++非类型模板参数const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆