gpt4 book ai didi

c++ - 将指针转换为模板参数 : Comeau & MSVC compile, GCC 失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:11 25 4
gpt4 key购买 nike

考虑以下代码:

template<int* a>
class base {};

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

Comeau 和 MSVC 都可以毫无问题地编译它(除了 Comeau 警告未使用的变量),而 GCC 在 base<(int*)0> test; 上失败行,说明

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

template argument 1 is invalid

它到底在提示什么?谁是对的——这段代码应该编译吗?值得注意的是,我的 GCC 版本非常旧 (3.4.2),所以这可能与它有关。谢谢。

最佳答案

来自draft standard (强调):

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,  ...

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

关于c++ - 将指针转换为模板参数 : Comeau & MSVC compile, GCC 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com