shepherd's Blog

[c++] namespace detail 본문

C,C++

[c++] namespace detail

shepherd.dev 2018. 11. 28. 22:32
test.md

namespace detail

opensource library를 보다 보면 namespace detail, impl 이라는 namespace를 정의한다.

이는 라이브러리에서 사용자에게 library의 API 로서 젝공될 부분만 공개하고 제공될 필요가 없는 부분을 의미한다. 그 외 실제 구현 부분은 internal namespace 로서 감추기 위해 사용되는 부분이다.

비슷한 의미로 internal, impl, implementaion, detail 등등 여러 단어로 사용되어진다.

예를 들어 아래와 같이 openssl wrapping 라이브러리를 만들고자 한다. 여기서 사용자에게 공개되는 라이브러리 인터페이스는 namespace crypt까지이며 그 내부 구현인 detail은 라이브러리를 사용하는 사용자에게 보이지 않게 된다. 실제 구현 부분은 cpp 파일에서 구현되며 생성된 라이브러리 파일로 감춰지게 된다.

sample code

  • sha_detail.hpp
    // sha_detail.hpp #ifndef __SHA_DETAIL_HPP__ #define __SHA_DETAIL_HPP__ namespace library { namespace crypt { namespace detail { std::string sha512_detail(const std::string& plain); } // namespace detail } // namespace crypt } // namespace library #endif // __SHA_DETAIL_HPP__
  • sha_detail.cpp
    // sha_detail.cpp #include <openssl/sha.h> #include "sha_detail.hpp" namespace library { namespace crypt { namespace detail { std::string sha512_detail(const std::string& plain) { // sha512 function implementation } } // namespace detail } // namespace crypt } // namespace library
  • sha.hpp
    // sha.hpp #ifndef __SHA_HPP__ #define __SHA_HPP__ #include <string> namespace library { namespace crypt { std::string sha512(const std::string& plain); } // namespace crypt } // namespace library #endif // __SHA_HPP__
  • sha.cpp
    // sha.cpp #include "sha.hpp" #include "sha_detail.hpp" namespace library { namespace crypt { inline std::string sha512(const std::string& plain) { return sha512_detail(const std::string& plain); } } // namespace crypt } // namespace library
  • build
    # build command g++ -o sha_detail.o sha_detail.cpp -I./ g++ -o sha.o sha.cpp -I./


이처럼 namespace를 분리할 경우 아래와 같은 이점이 있다.

  • hiding

    • namespace로 불필요하게 외부로 제공되는 부분을 분리할 수 있다.
    • library::crypt::detail은 라이브러리 내부에서 사용하는 함수이며, library::crypt가 외부로 제공될 함수 모음이다.


'C,C++' 카테고리의 다른 글

std::tie, std::tuple  (0) 2019.08.04
[C/C++] 함수 포인터  (0) 2015.09.16