[英]Hiding free functions
Lets say I have a bunch of free functions, within a particular namespace, which are covered by unit-tests. 假设我在一个特定的命名空间中有一堆免费函数,这些函数由单元测试覆盖。 And lets say I see some common functionality that can be moved out into a separate free function.
我们可以说,我看到了一些可以移动到单独的自由函数中的常用功能。 What can I do such that this new function becomes hidden?
我该怎么做才能隐藏这个新功能? In other words, this function should only be used by the aforementioned free functions and not elsewhere.
换句话说,此功能仅应由上述自由功能使用,而不能在其他地方使用。 Should I added it to a namespace under the free functions' namespace.
我应该将它添加到自由函数命名空间下的命名空间中吗? If so, what should I call the namespace - is there a naming convention?
如果是这样,我应该怎么称呼命名空间 - 是否有命名约定?
I should also point out that this new function is not unit tested since it is used internally by other functions that are unit-tested. 我还应该指出,这个新功能不是单元测试的,因为它是由其他经过单元测试的功能在内部使用的。 Perhaps I'm being lazy and the solution to this question is that I simply unit-test this function also and then people can use it if they want.
也许我是懒惰的,这个问题的解决方案是我只是对这个功能进行单元测试,然后人们可以根据需要使用它。
You can hide it: make it a private static member function of a class, and then explicitly friend each of your inline functions. 您可以隐藏它:使其成为类的私有静态成员函数,然后明确地与每个内联函数相关联。 The implementation could be in- or out-of-line, access control will still work.
实施可能是内部或外部的,访问控制仍然有效。
Unless you need to restrict access though, I'd follow the Boost convention and just put it in a nested namespace called detail
(or something similar). 除非您需要限制访问,否则我将遵循Boost约定并将其放在名为
detail
(或类似的东西)的嵌套命名空间中。 This is just intended to document that it is an implementation detail, rather than a stable public interface (and to avoid polluting the namespace, of course). 这只是为了记录它是一个实现细节,而不是一个稳定的公共接口(当然,为了避免污染命名空间)。
This also avoids having to explicitly list each free function as a friend. 这也避免了必须将每个自由函数明确地列为朋友。
You could have the helper function as a static function in the private section of a class and then only friend the functions that are allowed to use it. 您可以将辅助函数作为类的私有部分中的静态函数,然后只使用允许使用它的函数。
class Foo
{
static int helper() {return 0;}
friend void baz();
};
void baz()
{
Foo::helper(); //compiles
}
void buz()
{
Foo::helper(); //doesn't compile
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.