有没有一种方法可以使函数仅在c ++中通过参数传递的函数中可用?

时间:2020-04-12 17:50:41

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

我想处理我的函数中的错误。我决定使用该函数的可调用参数来执行此操作。因此,当“用户”将要调用该“危险”功能时,他可以指定将要执行的操作,例如lambda表达式。我希望用户可以在“用户范围”中无法访问的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

1 个答案:

答案 0 :(得分: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