Hemil
Hemil

Reputation: 1016

GCC 10.2 not accepting an lambda empty lambda as a constexpr std::function<void()>

I was playing around with constexpr when I found that GCC rejected this seemingly valid code:

#include <functional>

constexpr void test(const std::function<void()>& a) {
    a();    
}

int main() {
    test([](){});
}

I went to godbolt, and clang happens to compile this code fine. Is this a bug in GCC? Here is the godbolt link

Upvotes: 3

Views: 109

Answers (1)

Klaus
Klaus

Reputation: 25623

As already mentioned in the comments, std::function itself can not be used in constexpr environemt, because the operator()() and also the constructor of std::function is not constexpr.

As this you can use directly a pointer to function, if you have capture less lambdas or you can templatize you function like this in C++20:

constexpr void test(auto&& a) {
    a();
}

or with explicit template parameters in older C++ standards.

Use auto or auto& or auto&& as needed to allow temporary lambda, move it in or copy it ( which might be the same after optimizing )

Taken from the comments:

A constexpr function must have at least one set of inputs that are able to be evaluated in a constant expression - otherwise it's ill formed no diagnostic required*

As clang did not report something did not mean it is a clang bug.

Upvotes: 2

Related Questions