首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何初始化指向操作符重载的函数指针的向量?

如何初始化指向操作符重载的函数指针的向量?
EN

Stack Overflow用户
提问于 2018-05-07 15:03:43
回答 2查看 145关注 0票数 1

我试图从指向四个操作符重载成员函数的指针中生成一个std::vector。这是怎么回事?

代码语言:javascript
复制
struct Fractal
{   int dividee;
    int divisor;

    Fractal operator +(Fractal other)
    {   [not important]
    }

    Fractal operator -(Fractal other)
    {   [not important]
    }

    Fractal operator *(Fractal other)
    {   [not important]
    }

    Fractal operator /(Fractal other)
    {   [not important]
    }
};

int main()
{   Fractal fractal = Fractal{3, 10};

    typedef Fractal(*fractalOperator)(Fractal, Fractal);
    std::vector<fractalOperator> ops =
    {   &Fractal::operator +,
        &Fractal::operator -,
        &Fractal::operator *,
        &Fractal::operator /
    };
}

编译器说

代码语言:javascript
复制
error: could not convert '{&Fractal::operator+, &Fractal::operator-, &Fractal::operator*, &Fractal::operator/}' from '<brace-enclosed initializer list>' to 'std::vector<Fractal (*)(Fractal, Fractal)>'
 };

这不是很有帮助。正确的方法是什么?我在用c++14。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-07 17:49:07

您的typedef是指向函数的指针,它接受两个Fractals并返回一个Fractal。您需要的是一个指向成员函数的指针,它具有不同的语法。

代码语言:javascript
复制
typedef Fractal(Fractal::*fractalOperator)(Fractal);

或者,使用using别名,我觉得它更容易读懂

代码语言:javascript
复制
using fractalOperator = Fractal(Fractal::*)(Fractal);
票数 2
EN

Stack Overflow用户

发布于 2018-05-07 20:30:39

这样做的一种方法是:

代码语言:javascript
复制
std::vector<std::function<Fractal(Fractal, Fractal)>> ops = {
    [](Fractal l, Fractal r){ return l + r; },
    [](Fractal l, Fractal r){ return l - r; },
    [](Fractal l, Fractal r){ return l * r; },
    [](Fractal l, Fractal r){ return l / r; },
};

这样做的好处是,运算符是作为成员函数实现的,还是作为空闲函数实现的,这并不重要。

在封面下,lambda存储在具有正确调用签名的function对象中,而这些对象存储在vector中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50217236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档