如何使容器的元素只能调用容器一个私有函数的结构

How to make structure where container's element can call containers only one private function

本文关键字:一个 函数 结构 元素 何使容 调用      更新时间:2023-10-16

我想制作一个结构,其中容器元素可以向集装箱发出回调,但我不想让它成为public。我该怎么做?我不能保证,也许我需要静态地给容器的私有函数对元素的地址,或者以某种方式使用friend?顺便说一句,元素应该"查看"其他容器的私有函数。

例如,class Cont存储class ElemCont具有私有函数void callback();Elem知道他在哪个Cont中,并且可以调用回调函数Cont之外的任何人都不能使用回调函数

Elem构造函数中,您可以为回调设置一个参数(例如使用std::function或类似方法(,并将其存储在Elem类中。然后,当需要调用回调时,只需调用它即可。

您也可以在Elem中创建一个"setter"函数来设置回调。


完整示例

#include <iostream>
#include <string>
#include <functional>
#include <vector>
class Elem
{
private:
    int value_;
    std::function<void(const std::string&)> callback_;
public:
    Elem(int v, std::function<void(const std::string&)> cb)
        : value_{v}, callback_{cb}
    {}
    void some_function() const
    {
        callback_("Elem with value " + std::to_string(value_));
    }
};
class Cont
{
private:
    std::vector<Elem> elements_;
    void private_function(const std::string& s)
    {
        std::cout << "In private function: " << s << 'n';
    }
public:
    void add_value(const int v)
    {
        elements_.push_back(Elem(v, std::bind(&Cont::private_function, this, std::placeholders::_1)));
    }
    std::vector<Elem>::const_iterator begin() const
    {
        return std::begin(elements_);
    }
    std::vector<Elem>::const_iterator end() const
    {
        return std::end(elements_);
    }
};
int main()
{
    Cont c;
    // Add some elements
    for (int i = 1; i <= 10; ++i)
        c.add_value(i);
    // Call callback function
    for (const auto& e : c)
        e.some_function();
}

输出:

在私有函数中:值为1的Elem在私有函数中:值为2的Elem在私有函数中:值为3的Elem在私有函数中:值为4的Elem在私人功能中:值为5的Elem在私人功能中:Elem值为6在私人功能中:Elem值为7在私人功能中:Elem值为8在私人功能中:Elem值为9在私人功能中:Elem值为10

看看它在行动中。

在上面的代码中,私有函数Cont::private_function对于Elem类来说是完全未知的,不能直接调用。但是,我们可以使用参数将它传递给Elem类,然后从Elem类内部调用它,而不公开私有函数。