c++ bind绑定静态重载成员函数

在用bind绑定静态重载成员函数时提示“无法确定需要哪个重载函数”错误,在网上找了可以强制绑定的方法。

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>

struct MyStruct
{
    int a;
    std::string c;
    int b;
};
class asad
{
public:
    static bool com(MyStruct a, MyStruct b, int ae)
    {
        return a.a > b.a;

    }

    static bool com(MyStruct a, MyStruct b, bool ae)
    {
        return a.a > b.a;

    }

    bool comps(MyStruct a, MyStruct b, int ae)
    {
        return a.a > b.a;

    }

    bool comps(MyStruct a, MyStruct b, bool ae)
    {
        return a.a > b.a;

    }
};


static bool comp(MyStruct a, MyStruct b, int ae)
{
    return a.a > b.a;

}

static bool comp(MyStruct a, MyStruct b, bool ae)
{
    return a.a > b.a;

}


int main()
{
    std::vector<MyStruct> vec;
    for (int i = 0; i < 3; i++)
    {
        MyStruct a;
        a.a = i;
        a.c = std::to_string(3-i);
        vec.emplace_back(a);
    }
    asad a;

    //绑定静态重载成员函数
    std::function<bool(MyStruct, MyStruct)> fn1 = std::bind((bool(*)(MyStruct, MyStruct, int))&asad::com, std::placeholders::_1, std::placeholders::_2, 0);

    //绑定重载成员函数
    std::function<bool(MyStruct, MyStruct)> fn2 = std::bind((bool(asad::*)(MyStruct, MyStruct, int))&asad::comps, a, std::placeholders::_1, std::placeholders::_2, 0);

    //绑定静态函数
    std::function<bool(MyStruct, MyStruct)> fn3 = std::bind((bool(*)(MyStruct, MyStruct, int))comp, std::placeholders::_1, std::placeholders::_2, 0);

    std::sort(vec.rbegin(), vec.rend(), fn3);
    for (auto it :vec)
    {
        std::cout << it.a << std::endl;
    }
}

 

posted @ 2020-12-17 09:16  秦道友  阅读(601)  评论(0编辑  收藏  举报