Compare of std::function with lambda

2019-07-21 04:02发布

How to compare of std::function with lambda?

#include <iostream>
#include <functional>
using namespace std;

int main()
{
    using Type = void( float, int );
    std::function<Type> a;
    auto callback = []( float d, int r )
    {
        cout << d << " " << r << endl;
    };  
    static_assert( std::is_same< Type , decltype( callback ) >::value, "Callbacks should be same!" );


    a(15.7f, 15);   
}

Because in case of first parametr of lambda would be int - code would compile with 1 warning. How to protect code?

标签: c++ c++11 lambda
1条回答
Bombasti
2楼-- · 2019-07-21 04:14

The type of the callback is not a simple function. A lambda with no captures can decay to function pointer but it isn't a function pointer. It's an instance of a local class.

If you want to ensure a specific function type for a lambda, you can do that by forcing the decay to function pointer type:

#include <iostream>
#include <functional>
using namespace std;

int main()
{
    using Type = void( float, int );
    std::function<Type> a;
    auto callback = []( float d, int r )
    {
        cout << d << " " << r << endl;
    };  

    // Ensures desired type.
    {
        Type* const func_ptr = callback;   (void) func_ptr;
    }

    a = callback;
    a(15.7f, 15);   
}
查看更多
登录 后发表回答