Home >Backend Development >C++ >Why Does C 11 Type Deduction Fail with Lambdas in Function Templates?

Why Does C 11 Type Deduction Fail with Lambdas in Function Templates?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 09:00:35554browse

Why Does C  11 Type Deduction Fail with Lambdas in Function Templates?

C 11 Type Deduction Limitations with Lambda Functions

When working with lambda functions and std::function in C 11, type deduction may not be performed as expected, leading to errors.

The Issue

Consider the following function template:

template<class A>
set<A> filter(const set<A>& input, function<bool(A)> compare);

When calling this function with a lambda function directly, for example:

filter(mySet, [](int i) { return i % 2 == 0; });

an error will occur due to the compiler's inability to infer the template type for A.

Explanation

Lamda functions, while providing convenient syntax for anonymous functions, are distinct types that implement the operator() method. They are not directly supported by type deduction, which expects exact types.

Solutions

Several workarounds exist to address this issue:

  • Explicitly provide template type:
set<int> myNewSet = filter<int>(mySet, [](int i) { return i % 2 == 0; });
  • **Create an std::function:
std::function<bool(int)> func = [](int i) { return i % 2 == 0; };
set<int> myNewSet = filter(mySet, func);
  • Use a modified function template:
template<class A, class CompareFunction>
set<A> filter(const set<A>& input, CompareFunction compare);

In this modified template, the type CompareFunction represents a function object that takes an A argument and returns a boolean. The template parameter is no longer deduced, but explicitly specified.

Additional Features

With the new decltype keyword and function return type syntax, the function can be further generalized to automatically determine the return type:

template<class Value, class CompareType, class IndexType>
auto filter(const set<Value>& input, CompareType compare, IndexType index) -> map<decltype(index(*(input.begin()))), Value> { ... }

This template function expects three types: the input set value type, the comparison function type, and the index function type. The return type is automatically determined and instantiated.

The above is the detailed content of Why Does C 11 Type Deduction Fail with Lambdas in Function Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn