xaxxon
xaxxon

Reputation: 19771

Does a function pointer need to point to a function with external linkage when used as a template parameter?

In the code below, on the first form, gcc complains about having a lambda in a template parameter. In the second form, gcc complains about lambda_function_pointer not having external linkage. Clang compiles and runs the code just fine even with -pedantic.

The + in front of the lambda is to coerce it to decay into a function pointer.

template<auto f>
void func() {
    f();
}
void g();
int main() {
    func<+[](){}>();  // gcc complains about lambda in template args

    constexpr auto lambda_function_pointer = +[](){};
    func<lambda_function_pointer>(); // gcc complains about not having external linkage

}

live: https://godbolt.org/g/ey5uo7

Thank you.

edit: https://timsong-cpp.github.io/cppwp/n4659/expr.prim.lambda#2 mentions lambdas not appearing in template parameters for the sake of the lambda not being in the signature, but with the +, it gets rid of the lambda type.

edit2: This may be relevant for the linkage portion of the question: Why did C++03 require template parameters to have external linkage?

Upvotes: 8

Views: 224

Answers (1)

T.C.
T.C.

Reputation: 137325

func<+[](){}> is ill-formed in C++17 per the exact paragraph you linked to. The non-normative note simply explains the motivation for the normative prohibition. It does not - and cannot - limit it. This restriction has been removed in the current working draft by P0315, so it has a good chance of making C++20.

Pre-C++17, a lambda-expression cannot be evaluated inside constant expressions.

The "linkage" part is a duplicate of Can I use the result of a C++17 captureless lambda constexpr conversion operator as a function pointer template non-type argument?. It's a GCC bug.

Upvotes: 3

Related Questions