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



我想处理函数中的错误。我决定在该函数中添加一个可调用的参数。因此,当一个"用户"要调用那个"危险"函数时,他可以指定要用lambda表达式执行的操作。我希望用户可以在lambda中调用某个在"users scope"中不可访问的函数(它可能可以从一些不同的隐藏范围访问,例如与危险函数相同的命名空间,或者嵌套在那里的更好的命名空间(。有办法做到这一点吗?

我可能会尝试将其作为参数传递给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;
}

但是getdescription((函数不在默认名称空间中

Passkey习语可能会有所帮助:

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

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
}

演示

最新更新