【问题标题】:Is there a way to make a function available only in a function passed through argument in c++?有没有办法使函数仅在通过 C++ 中的参数传递的函数中可用?
【发布时间】:2020-04-12 17:50:41
【问题描述】:

我想处理我的函数中的错误。我决定在该函数中使用一个可调用的参数。因此,当“用户”即将调用该“危险”函数时,他可以指定要执行的操作,例如拉姆达表达式。我希望用户可以调用在“用户范围”中无法访问的 lambda 中的某个函数(它可能可以从一些不同的隐藏范围访问,例如与危险函数相同的命名空间,或者嵌套在那里的更好的命名空间)有没有办法做这样的事情?

我可能会尝试将它作为参数传递给 lamda,但这需要用户了解该函数。如果 id 喜欢以这种方式公开多个函数,那就更糟了。

像这样:

#include "dangerous.hpp"
int main() {
   std::string error_description
   // call a function from dangerous.hpp
   dngr::doathing(
      "param1", "param2", "param3",
      [&error_description](int error_code){
         error_description = get_description(error_code);
         //                    ^
         // also provided by dangerous.hpp somehow
      }
   );


   return 0;
}

但 get_description() 函数在默认命名空间中无处可见(无需过多查看)definetley 不在默认命名空间中

【问题讨论】:

  • 我建议不要要求人们使用他们的想象力。显示一些尝试执行您所说的代码。
  • 抱歉,已编辑问题
  • 您提供的示例代码让我想知道为什么您传入错误代码而不是错误对象?错误对象可能带有成员方法来获取代码和描述。你能举个例子说明采用简单的面向对象方法是不够的吗?
  • 正如你所说的,这只是一个例子,但背后的想法是我只传递代码(没有额外的数据),并且错误的描述将被硬编码,所以除非实际出现错误,否则不会传递发生。如果我通过引用传递它,我可能想多了

标签: c++ function lambda error-handling scope


【解决方案1】:

密码习语可能会有所帮助:

首先,创建一个没有公共构造函数的结构,并使其成为您的某个类的朋友。

class Key
{
private: // All private
    friend class MyClass; // only MyClass can use it.

    Key() {}

    Key(const Key&) = delete;
    Key& operator=(const Key&) = delete;
};

现在,使用该参数声明要保护的函数:

void reset_password(const Key&, std::string);
std::string get_description(const Key&, int error_code);

然后,你的班级可能会要求一个合适的函子:

class MyClass
{
public:

    void doathing(
        std::string param1, std::string param2, std::string param3,
        std::function<void(const Key&, int)> func)
    {
        // ...
        auto error_code = 42;
        func({}, error_code);
    }
};

main():

int main()
{
    MyClass c;
    std::string error_description;
    c.doathing(
        "param1", "param2", "param3",
        [&error_description](const Key& key, int error_code){
            error_description = get_description(key, error_code);
        }
    );
    std::cout << error_description;
    // get_description({}, 42); // error: 'Key::Key()' is private within this context
}

Demo

【讨论】:

  • 这对我不起作用。我的目标只是方便地将函数插入到 lambda 中,而不会弄乱默认或 dngr 命名空间。但我真的很欣赏你的方法,这很有趣。我对你的答案投了赞成票,但我还没有足够的代表可以看到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多