c++ - 如何调用通过 constexpr 表达式返回 void 的 constexpr 函数?
问题描述
调用test
编译失败但test1
成功
constexpr void test(int n)
{
return;
}
constexpr int test1(int n)
{
return n;
}
int main()
{
constexpr test(5); // Failed
constexpr (test)(5); // Also failed
constexpr auto n = test1(5); // OK
return 0;
}
我可能会滥用某些东西,或者这不是一个真实的案例。请帮忙解释一下。我在 SO 上找不到同样的问题
输出:
<source>: In function 'int main()':
<source>:14:15: error: ISO C++ forbids declaration of 'test' with no type [-fpermissive]
14 | constexpr test(5); // Failed
| ^~~~
<source>:15:16: error: ISO C++ forbids declaration of 'test' with no type [-fpermissive]
15 | constexpr (test)(5); // Also failed
| ^~~~
解决方案
您使用了错误的语法。编译器会感到困惑,因为它希望您要声明一个名为的变量test
,并抱怨如果不声明其类型就无法做到这一点。这是编译器所期望的:
constexpr int test(5); // OK
constexpr int (test_x)(5); // also OK
这就是你真正想要的:
test(5);
(test)(5); // ok, but unusual to put the () here
您无需明确声明您正在调用constexpr
方法。constexpr
是声明的一部分,而不是函数调用的一部分。
推荐阅读
- javascript - 动态设置 className 字符串 Javascript \ React
- c# - 外人指的是什么?
- php - PHP:使用队列机制处理 csv 文件的最佳选择,以便在 mysql 数据库上进行大量插入
- python - 如何在列表中添加扩展名?
- python - Python requests.raise_for_status() 异常查找输出
- c# - 从子窗体访问主窗体中的控件
- spring - 创建spring项目时出错。: J2EE 组件映射更新
- java - 如何调用 Rest API 并使用该 API 中的数据?
- apache-spark - 使用 Java 在 Spark 中进行映射
- python - 安装 socail-auth-app 后 Django 中的 ModuleNotFoundError