2011-11-17 2 views
6

일부 템플릿 함수가있는 라이브러리를 작성하려고합니다. 일부 함수는 도우미 함수이므로 사용자에게 액세스 권한을 부여하지 않으려합니다. 일부 기본 코드는템플릿 도우미 함수 숨기기 - 정적 멤버 또는 이름없는 네임 스페이스

//mylib.h 

namespace myfuncs 
{ 
    template<class T> 
    void helper (T input, int extrainformation) 
    { 
     //do some usefull things 
    } 

    template<class T> 
    void dostuff(T input) 
    { 
     int someinfo=4; 
     helper(input, someinfo); 
    } 
} 

도우미 기능을 숨겨서 라이브러리 사용자가 직접 호출 할 수 없도록 할 수 있습니까? 명명되지 않은 네임 스페이스가 작업을 수행 할 수 있다고 생각했지만 템플릿을 사용하기 때문에 헤더와 구현 파일간에 함수 선언과 본문을 나눌 수 없습니다. 이름없는 네임 스페이스를 헤더 파일에 두는 것은 아무 쓸모가없고 나쁜 스타일입니다. 내가 생각할 수있는 유일한 방법은 mylib 클래스를 만들고 함수를 private/public static 함수로 캡슐화하는 것입니다.

더 좋은 해결책은 많이 주시면 감사하겠습니다.

필 그것을 할

+1

나는 변화를 제안'namespace' 'class'에 모든 함수를 정적으로 만들고,'helper'를'private'에 넣으십시오. – neuront

답변

8

한 가지 방법은 "세부 사항"또는 "내부"네임 스페이스를하는 것입니다. 얼마나 많은 도서관이 그렇게하는지.

namespace myfuncs 
{ 
    namespace detail 
    { 
     template<class T> 
     void helper (T input, int extrainformation) 
     { 
      //do some usefull things 
     } 
    } 

    template<class T> 
    void dostuff(T input) 
    { 
     int someinfo=4; 
     detail::helper(input, someinfo); 
    } 
} 
3

수행 무엇을 (아이겐 같은) 많은 템플릿 라이브러리를 수행합니다 (예 : myfuncs::impl 등) 명확라는 이름의 구현 고유의 네임 스페이스를 사용하고 즉, 사용자가 아닌 기꺼이이 구현에서 템플릿을 호출 (사회 캡슐에 의존 네임 스페이스).

+1

그리고 문서화 : 우리는'impl'에있는 것들을 제외하고는 안정적인 인터페이스를 보장합니다. 만약 당신이 의존한다면, 당신의 소프트웨어가 업그레이드 중에 중단되는지 상관하지 않습니다. –

0

할 수 있습니다 : header.h가에서
:

source.cpp에서
#ifndef AAA_H 
#define AAA_H 
namespace myfuncs 
{ 
    template<class T> 
    std::string dostuff(); 
} 
#include "aaa.cpp" 
#endif // AAA_H 

:

MAIN.CPP에서
#define AAA_CPP 
#include <string> 
namespace { 
    template<class T> 
    std::string helper() 
    { 
    return "asdf"; 
    } 
} 

namespace myfuncs 
{ 
    template<class T> 
    std::string dostuff() 
    { 
     return helper<T>(); 
    } 
} 
#endif // AAA_CPP 

:

#include <iostream> 
#include "aaa.h" 

int main(int argc, char *argv[]) 
{ 
    std::cout << myfuncs::dostuff<std::string>(); 
    return 0; 
} 
관련 문제