C++ template lambda function cannot be passed to the factor.

Asked 2 years ago, Updated 2 years ago, 57 views

//
//  //  main.cpp
//  //  test
//
//  //  Created by bodguy on 2016. 8. 22..
//  Copyright © 2016 bodguy. All rights reserved.
//

#include <iostream>
#include <functional>
#include <type_traits>

template<typename T, typename = std::enable_if_t<std::is_integral<T>::value || std::is_floating_point<T>::value > >
void add(T p, const std::function<bool(T,T)>& func) {
    std::cout << std::boolalpha;
    std::cout << func(p,p+1) << std::endl;
}

int main(int argc, const char * argv[]) {
    const std::function<bool(float,float)>& f = [](float a, float b){return a < b;};
    add(10.2f, f);
    // Why can't I do the one below?
    // // add(10.2f, [](float a, float b){return a < b;});
    return 0;
}

In the above code, add (10.2f, f); is called properly, but if you transfer the lambda expression to the factor, Is there a compilation error?

c++ stl

2022-09-22 11:03

1 Answers

I don't know exactly, but let me write down my thoughts.

The problem seems to be caused by the difficulty of type inference.

Use the template<typename F>function(Ff) constructor to generate function by entering a lambda. At this point, you can enter a lambda that can be called to match the template factor of the function class template.

For function<bool(float, float)>, [](double, float) {...} and [](double, double) {...} can also be entered.

In other words, [](float a, float b){return a < b;} alone cannot infer which function template class.

If T is the same by inferring float through 10.2f which is the first factor entered in add and inferring the type through the second factor, Lambda.> will be instantiated, but compilation error seems to occur because T is difficult to infer from second factor.

Therefore, if the template factor for T is specified as below, the compilation can be successful because the type of the second parameter of add can be inferred and the lambda can be converted to function<bool(float, float)>.

 add<float>(10.2f, [](float a, float b){return a < b;});


2022-09-22 11:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.