首页 > 解决方案 > 如何调用通过 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
      |                ^~~~

标签: c++constexpr

解决方案


您使用了错误的语法。编译器会感到困惑,因为它希望您要声明一个名为的变量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是声明的一部分,而不是函数调用的一部分。


推荐阅读