2011-11-28 58 views
9

在類作用域聲明typedef是不好的做法嗎?爲每個函數聲明它們是否更好,以確保沒有人包含該文件,然後創建具有相同名稱的東西?Class scope typedef壞習慣?

例如

typedef std::vector<int>::size_type vec_int; 

在一些班級有使用這種類型的許多功能,但在另一方面,我將不得不把它的頭將是我的一些標題是有用的,止跌我嗎?或者我可以把它放在源文件的頂部嗎?

+0

我想我不明白你爲什麼問。你有沒有聽到? –

+0

哈哈,呃,什麼?這是來自一首歌嗎? – SirYakalot

+0

在你的例子中沒有typedef ... – interjay

回答

13

我想說的只是保持最小範圍;與此同時,做任何最乾淨的事情。

如果您將它用於某個功能,請將其保留在該功能的範圍內。如果您將它用於多種功能,請將其設置爲私有typedef。如果您希望其他人使用它(可能沒有用),請將其公開。

在代碼:

namespace detail 
{ 
    // By convention, you aren't suppose to use things from 
    // this namespace, so this is effectively private to me. 

    typedef int* my_private_type; 
} 

void some_func() 
{ 
    // I am allowed to go inside detail: 
    detail::my_private_type x = 0; 

    /* ... */ 
} 

void some_other_func() 
{ 
    // I only need the typedef for this function, 
    // so I put it at this scope: 
    typedef really::long::type<int>::why_so_long short_type; 

    short_type x; 

    /* ... */ 
} 

typedef int integer_type; // intended for public use, not hidden 

integer_type more_func() 
{ 
    return 5; 
} 

class some_class 
{ 
public: 
    // public, intended for client use 
    typedef std::vector<int> int_vector; 

    int_vector get_vec() const; 

private: 
    // private, only for use in this class 
    typedef int* int_ptr; 
}; 

希望,讓你我的意思的想法。

+0

它是否合法,將它放在實現文件的include指令下?私人會員是一個很好的解決方案,我只是對可能性感到好奇。 – SirYakalot

+1

@SirYakalot:是的,這只是文件範圍(全局)。如果你想模仿免費函數的私有typedef,那麼通常有一個不應該被客戶端訪問的'detail'命名空間。 – GManNickG

+0

你會說什麼是更好的做法?一個私人會員還是把它放在源頭的頂部? – SirYakalot

11

Class scope typedefs非常好,它們不能與類作用域之外的任何東西衝突。

標準庫與類範圍的typedef(value_typepointerreferenceiteratorconst_iterator等等等等)分組。