指针非类型模板参数 [英] pointer non-type template parameter

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

问题描述

我不太明白为什么下面的代码不能编译:

I don't really understand why the code below does not compile:

template<const char*>
struct Foo{};

constexpr const char s1[] = "test1";
constexpr const char* const s2 = "test2";

int main()
{
    Foo<s1> foo1; // ok
    // Foo<s2> foo2; // doesn't compile
}

取消注释 main()使g ++和clang ++发出错误

Uncommenting the last line in main() makes g++ and clang++ emit the errors


error: 's2' is not a valid template argument because 's2' is a
variable, not the address of a variable


的地址


error: non-type template argument for template parameter of
      pointer type 'const char *' must have its address taken


分别。

我的问题是:


  1. 为什么 s1 实例化可以,而 s2 实例化不能?

  2. 有没有理智的情况可以使用此类指针非类型模板参数?

  1. Why is s1 instantiation OK and s2 not?
  2. Is there any sane situation where such pointer non-type template parameter is of any use?


推荐答案

对于1。:

来自[temp.arg.nontype]

From [temp.arg.nontype]


1非参数的模板参数型t emplate-parameter必须是模板参数类型的转换后的常数表达式(5.20)。对于引用或指针类型的非类型模板参数,常量表达式的值不得引用(;对于指针类型,其值不得为的地址):

[...]

(1.3)-字符串文字(2.13.5),

(1.3) — a string literal (2.13.5),

s2 保存字符串文字的地址,因此不能在此处用作参数。另一方面, s1 char 的数组,该数组已用字符串进行初始化文字,但是 s1 的值(当转换为 const char * 时)不指向所使用的字符串文字在初始化中。

s2 holds the address of a string literal, and so cannot be used as the parameter here. s1 on the other hand is an array of char that has been initialized with a string literal, but the value of s1 (when converted to const char*) doesn't point to the string literal used in the initialization.

对于2:

函数指针?仍然我不能说我曾经使用过指针作为非类型参数。

Function pointers perhaps? Still I can't say I've ever used a pointer as a non-type parameter.

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

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