简体   繁体   English

隐藏头文件中的非成员函数

[英]Hiding non-member functions in header files

I'm wondering if I can define some functions in a header file and then use them in the same header file, while hiding them from anything else? 我想知道我是否可以在头文件中定义一些函数然后在同一个头文件中使用它们,同时将它们隐藏在其他任何东西中?

For example, can I first define some general helper functions(specific to the data-structures), and then define some data-structures in the same header that use those functions? 例如,我可以首先定义一些通用辅助函数(特定于数据结构),然后在使用这些函数的同一个头中定义一些数据结构吗?

eg: 例如:

template<class T>
void Swap(T &a, T &b)
{
  T temp = a;
  a = b;
  b = temp;
}

But I don't want Swap() to interfere with other functions that have the same name. 但我不希望Swap()干扰其他具有相同名称的函数。

I could make it a private method, but then I'd have to provide every class that uses it with the same implementation or make them friend class... 我可以使它成为一个私有方法,但是我必须提供使用它的每个类具有相同的实现或者使它们成为朋友类...

Traditionally, the namespace details is used for implementation-reserved stuff that has to go in a header. 传统上,命名空间details用于必须在标头中的实现保留的东西。

Also, there's a std::swap , so no need for your own. 此外,还有一个std::swap ,所以不需要你自己的。

You usually can't hide the function completely from other clients but you can put it in its own namespace so that it doesn't interfere with client code. 您通常无法完全隐藏其他客户端的功能,但您可以将其放在自己的命名空间中,这样它就不会干扰客户端代码。 A common practice is to make the namespace an inner namespace of your main library namespace and to call it details or something similar. 通常的做法是使命名空间成为主库命名空间的内部命名空间,并将其称为details或类似内容。

Of course, if you need to function to be available through ADL then it has to live in the namespace enclosing the classes for which the ADL is supposed to match. 当然,如果你需要通过ADL提供函数,那么它必须存在于包含ADL应该匹配的类的命名空间中。 There's no way around this. 没有办法解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM