Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

gcc

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

like image 591
Hemil Avatar asked Aug 03 '26 09:08

Hemil


1 Answers

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.

like image 76
Klaus Avatar answered Aug 06 '26 02:08

Klaus