Forcing inlining of lambda in MSVC C++

Viewed 822

Next code compiles in CLang/GCC, and successfully inlines lambda:

Try it online!

#include <iostream>

int main() {
    int x = 0;
    auto f = [&]() __attribute__((always_inline)) {
        ++x;
    };
    f();
    std::cout << x;
}

But similar code with __forceinline in latest MSVC (2019 v16.8.3) doesn't compile, although was announced as implemented in v16.7:

Try it online!

#include <iostream>

int main() {
    int x = 0;
    auto f = [&]() __forceinline {
        ++x;
    };
    f();
    std::cout << x;
}

throwing compile error 0305.cpp(5): error C3260: 'type': skipping unexpected token(s) before lambda body.

Is it really not yet implemented or am I using __forceinline in a wrong place? Is there any other way to force inlining of lambda in MSVC?

Also is there any way in all of popular compilers (e.g. CLang/GCC/MSVC) to not compile code (and throw compiling error) in case if given lambda was used in some place without being inlined? Also does __attribute__((always_inline)) and __forceinline in all 100% of use cases guarantee that lambda is definitely inlined?

1 Answers

Per Jonathan Caves reply on the feature request, the supported syntax going forward is

auto f = [&]() [[msvc::forceinline]] {
    ++x;
};

which does compile

It looks like they wanted it to comply with the attributes syntax that was introduced in C++11

Related