将指针作为模板参数:Comeau& MSVC编译,GCC失败 [英] Casting pointer as template argument: Comeau & MSVC compile, GCC fails

查看:161
本文介绍了将指针作为模板参数:Comeau& MSVC编译,GCC失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

template<int* a>
class base {};

int main()
{
    base<(int*)0> test;
    return 0;
}

Comeau和MSVC编译时没有问题(Comeau警告变量),而GCC在 base <(int *)0>上失败。测试; 行,说明

Both Comeau and MSVC compile this without issues (except for Comeau warning about an unused variable), while GCC fails on the base<(int*)0> test; line, stating


在函数`int main()'中:
a转换为非整数或枚举类型的类型不能出现在常量表达式中

In function `int main()': a casts to a type other than an integral or enumeration type cannot appear in a constant-expression

模板参数1无效

它抱怨究竟是什么?谁是对的 - 这段代码应该编译吗?值得注意的是,我的GCC版本是非常 old(3.4.2),所以可能与它有关。感谢。

What exactly is it complaining about? And who's right -- should this code compile? It's worth noting that my GCC version is extremely old (3.4.2) so that may have something to do with it. Thanks.

推荐答案

标准草案(着重号添加):


14.1.3 A non-type template-parameter shall have one of the following (option-
  ally cv-qualified) types:
  ...
  --pointer to object, accepting an address constant  expression  desig-
    nating a named object with external linkage,
  ...

显然,使用空指针来实例化模板是不合法的,因为空指针不会指向具有外部链接的命名对象。

Apparently, it's not legal to instantiate a template with a null pointer, as a null pointer doesn't point to a "named object with external linkage".

这篇关于将指针作为模板参数:Comeau&amp; MSVC编译,GCC失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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