简体   繁体   中英

How to call a constexpr function which returns void by a constexpr expression?

The call to test failed to compile but test1 succeeded

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;
}

I could misuse something or it is not a real case. Please help to explain. I cannot not find the same question on SO

Output :

<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
      |                ^~~~

Your are using the wrong syntax. The compiler gets confused because it expects that you want to declare a variable called test and complains that you cannot do that without declaring its type. This is what the compiler expects:

constexpr int test(5);     // OK
constexpr int (test_x)(5); // also OK

And this is what you you actually want:

test(5);
(test)(5);  // ok, but unusual to put the () here

You do not need to explicitly state that you are calling a constexpr method. constexpr is part of the declaration, not of the function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM