简体   繁体   English

将函子传递给模板化函数

[英]Passing a functor into a templated function

I am new to templating, but I am trying to make my primms algorithm work with two different distance calculators(thats what the functors are for) based on different constraints for a school project (they calculate the distance differently, one depends on if we care about terrain and the other does not).我是模板的新手,但我试图让我的 primms 算法根据学校项目的不同约束使用两个不同的距离计算器(这就是函子的用途)(它们计算距离的方式不同,一个取决于我们是否关心关于地形,其他没有)。 I declare like this我这样声明

template <typename func>
    double mst_mode(std::vector<primms_vertex> &mst_vec, const func &comp){

But later in the function when I attempt to use it like this:但是稍后在函数中,当我尝试像这样使用它时:

if(i != working_vertex && !mst_vec[i].been_visited && mst_vec[i].distance > comp(mst_vec[working_vertex], mst_vec[i])){

I get the following errors :我收到以下错误:

No matching function for call to object of type 'const primms_vertex::euclids_distance' No matching function for call to object of type 'const primms_vertex::primms_distance'没有用于调用类型为“const primms_vertex::euclids_distance”的对象的匹配函数没有用于调用类型为“const primms_vertex::primms_distance”的对象的匹配函数

One example of me calling the function is:我调用该函数的一个例子是:

poke->mst_mode(poke->primms_vector, primms_vertex::primms_distance());

(the project is pokemon themed so excuse the funny class name) Both of the functors take in the exact same thing, 2 mst_vertex's, which is exactly what I am getting when I index into mst_vec. (该项目以 pokemon 为主题,所以请原谅有趣的类名)两个函子都采用完全相同的东西,2 mst_vertex,这正是我索引 mst_vec 时得到的。 So I cannot figure out for the life of me what the compiler is complaining about.所以我一生都无法弄清楚编译器在抱怨什么。 Any help would be appreciated!任何帮助,将不胜感激!

Something like this:像这样的东西:

#include <vector>

struct primms_vertex {
    bool been_visited{};
    size_t distance{};
    static size_t primms_distance(primms_vertex const& left, primms_vertex const& right);
};

size_t primms_vertex::primms_distance(primms_vertex const& left, primms_vertex const& right) {
    return left.distance < right.distance;
}

struct Poke {
    std::vector<primms_vertex> primms_vector;

    template <typename func>
    double mst_mode(std::vector<primms_vertex>& mst_vec, const func& comp) {
        size_t working_vertex{ 42 };
        for (size_t i = 0; i < mst_vec.size(); i++) {
            if (i != working_vertex && !mst_vec[i].been_visited && mst_vec[i].distance > comp(mst_vec[working_vertex], mst_vec[i])) {
                // do something.
            }
        }
        return 0.0;
    }

};

int main() {
    Poke* poke{}; // TODO: Instantiate a Poke.
    poke->mst_mode(poke->primms_vector, primms_vertex::primms_distance);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM