Home > Backend Development > C++ > Why Doesn't C 11 Deduce Types When Using Lambda Functions with Function Templates?

Why Doesn't C 11 Deduce Types When Using Lambda Functions with Function Templates?

Susan Sarandon
Release: 2024-12-17 21:04:10
Original
458 people have browsed it

Why Doesn't C  11 Deduce Types When Using Lambda Functions with Function Templates?

C 11 Does Not Deduce Type When Function or Lambda Functions Are Involved

When using C 11 templates or lambda functions, it is important to understand how type deduction works. In cases where you define a function template that accepts a std::function or lambda function, the compiler may not be able to automatically deduce the template type.

For example, consider the following function:

template<class A>
set<A> filter(const set<A>& input, function<bool(A)> compare) {
    set<A> ret;
    for(auto it = input.begin(); it != input.end(); it++) {
        if(compare(*it)) {
            ret.insert(*it);
        }
    }
    return ret;
}
Copy after login

If you try to call this function directly with a lambda function, you may encounter an error. This is because the compiler cannot deduce the template type from the lambda function alone:

set<int> myNewSet = filter(mySet,[](int i) { return i%2==0; });
Copy after login

This error can be avoided by explicitly specifying the template type:

set<int> myNewSet = filter<int>(mySet,[](int i) { return i%2==0; });
Copy after login

Alternatively, you can convert the lambda function to a std::function object:

std::function<bool(int)> func = [](int i) { return i%2 ==0; };
set<int> myNewSet = filter(mySet,func);
Copy after login

In cases where you need to filter a set of values based on a comparison function, you can provide a more generic solution by creating a function template that accepts a CompareFunction type:

template<class Value,class CompareFunction>
set<Value> filter(const set<Value>& input,CompareFunction compare) {
    set<Value> ret;
    for(auto it = input.begin(); it != input.end(); it++) {
        if(compare(*it)) {
            ret.insert(*it);
        }
    }
    return ret;
}
Copy after login

The above is the detailed content of Why Doesn't C 11 Deduce Types When Using Lambda Functions with Function Templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template