【问题标题】:C++ Reference to member function work around (computation speed)C++ 对成员函数的引用变通(计算速度)
【发布时间】:2022-11-03 05:04:06
【问题描述】:

众所周知,您不能在 C++ [source] 中创建对成员函数的引用。

对于那些不知道的人。当您想做类似的事情时,问题就来了

class A
{
public:
    void Add(int a, int b)
    {
        std::cout << "Sum is " << a + b << std::endl;
    }

    void CallAdd(int a, int b, void (*func)(int, int))
    {
        func(a, b);
    }
};

然后通过CallAdd调用Add:

A a;
a.Add(3, 7); // This works fine
a.CallAdd(3, 7, &a.CallAdd); //This does not compile

错误是

error: cannot create a non-constant pointer to member function
    a.CallAdd(3, 7, &a.CallAdd);

如果它在课堂之外,就不会发生这种情况。 有一个使用 std::function/lambda 的解决方法。像这样:

class A
{
public:
    function<void(int, int)> AddFunc = [](int a, int b)
    {
        std::cout << "Sum is " << a + b << std::endl;
    };

    void CallAdd(int a, int b, std::function<void(int, int)> &func)
    {
        func(a, b);
    };
};

int main()
{
    A a;
    a.CallAdd(3, 7, a.AddFunc);
}

这很好用,但问题是与简单地调用函数相比,计算时间增加了很多(显然这只是一个最小的可重现示例)。

有没有办法提高计算速度,或者这是最好的方法吗?

对于上下文,我有一个集成函数的算法,并且我想随意更改被积函数,因此被积函数必须是函数参数。

【问题讨论】:

  • 创建指向成员函数的指针的语法是&amp;A::Add

标签: c++ class reference member-functions function-reference


【解决方案1】:

将函数对象(或 lambda)传递给模板化成员函数,如下所示:

#include <concepts>
#include <iostream>

inline auto myAddFunc = [](int a, int b) {
    std::cout << "Sum is " << a + b << std::endl;
};

class A
{
public:
    template <std::regular_invocable<int,int> Func>
    void CallFunc(int a, int b, Func func)
    {
        func(a, b);
    };
};

int main()
{
    A a;
    auto mySubFunc = [](int a, int b) {
        std::cout << "Difference is " << a - b << std::endl;
    };
    a.CallFunc(3, 7, myAddFunc);
    a.CallFunc(7, 3, mySubFunc);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多