2011-11-17 58 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類,並將這些函數封裝爲私有/公共靜態函數。

任何更好的解決方案將不勝感激。

菲爾

+1

我建議改變'namespace'到'class'並將所有函數設置爲'static',然後將'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:

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

在source.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 

在main.cpp中:

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

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