gpt4 book ai didi

c++ - 为什么 `const` 指向函数的指针在常量表达式中不可用?

转载 作者:行者123 更新时间:2023-12-03 06:53:52 25 4
gpt4 key购买 nike

考虑以下模板:

using IntFnPtr = int(*)(int);
template <IntFnPtr> void f() { }

还有这些测试:

int g(int) { }

int main()
{
f<&g>(); // OK

const IntFnPtr cp = &g;
f<cp>(); // Error -- why?

constexpr IntFnPtr cexprp = &g;
f<cexprp>(); // OK
}

为什么用 cp 实例化 f 的尝试格式错误?编译器提示:

> error: no matching function for call to 'f'

live example on godbolt.org


请注意,这似乎与其他实体不一致,例如整数:

template <int> void f() { }

int main()
{
f<5>(); // OK

const int ci = 5;
f<ci>(); // OK

constexpr int cexpri = 5;
f<cexpri>(); // OK
}

最佳答案

首先,有 temp.arg.nontype#2 :

A template-argument for a non-type template-parameter shall be a converted constant expression ([expr.const]) of the type of the template-parameter.

[Note 1: If the template-argument is an overload set (or the address of such, including forming a pointer-to-member), the matching function is selected from the set ([over.over]). — end note]

然后我们可以跟随它到 expr.const#10 :

A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only ...

从该规则中,我们可以看出变量 cp 不可能是常量表达式,因为根据 expr.const#3 它甚至可能是常量 :

A variable is potentially-constant if it is constexpr or it has reference or const-qualified integral or enumeration type.

所以 cp 不是非类型模板参数的有效模板参数,您会得到一个错误。

请注意,这是与 ci 明显不一致的地方。由于 ci 具有 const 限定的整数类型,因此它可以用作非类型模板参数的模板参数。

同样,所有其他对 f 的调用也是允许的,因为在每种情况下模板参数都是常量表达式:

  1. g是一个有外部链接的函数,所以它的地址是一个常量表达式。

  2. 5 是常数积分表达式。​​

  3. cexprpcexpri 都是 constexpr 变量。

关于c++ - 为什么 `const` 指向函数的指针在常量表达式中不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64688292/

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