non-constexpr lambda marked constexpr should not compile

According to C++ 17, the following code should not compile:


1
2
3
4
5
auto squared2 = [](auto val) constexpr
{
    static int a = 1;
    return  val * val;
};


But in VStudio 2019 it compiles fine - only when I attempt to use it in a compile time context do I get an error, as in:

 
std::array<int, squared2(5)> a;


Is the compiler not fully C++ 17 compliant?

Regards,
Juan
The first version "explicitly specifies that the function call operator is a constexpr function. When this specifier is not present, the function call operator will be constexpr anyway, if it happens to satisfy all constexpr function requirements." https://en.cppreference.com/w/cpp/language/lambda

So I wonder what it's purpose is? Perhaps just to catch the "not a constexpr" error earlier in the parse. I guess VSC++ hasn't bothered to implement that yet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <array>

int main() {

#if 0
// This one gives this error (gcc) :
//   lambda.cpp:12:20: error: static variable not permitted in a
//         constexpr function

    auto squared1 = [](auto val) constexpr {
        static int a = 1;
        return  val * val;
    };
    //std::array<int, squared1(2)> a;    // error (not a constexpr)
    std::cout << squared1(2) << '\n';
#endif

#if 1
// This one doesn't give an error (until used).
    constexpr auto squared2 = [](auto val) {
        static int a = 1;
        return  val * val;
    };
    //std::array<int, squared2(2)> a;    // error (not a constexpr)
    std::cout << squared2(2) << '\n';
#endif

#if 1
    // Neither constexpr is needed for it to be constexpr.
    /*constexpr*/ auto squared3 = [](auto val) /*constexpr*/ {
        return  val * val;
    };
    std::array<int, squared3(2)> a;
    std::cout << squared3(2) << '\n';
#endif
}

Last edited on
Makes sense... I agree VStudio hasn't implemented this error reporting
thanks
Registered users can post here. Sign in or register to post.