簡體   English   中英

類范圍typedef不好的做法?

[英]Class scope typedef bad practice?

在類范圍聲明typedef是不好的做法嗎? 為每個函數聲明它們以確保沒有人包含該文件然后創建具有相同名稱的東西更好嗎?

例如

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

在我的一些標題中會有用,因為在某些類中有許多使用此類型的函數,但另一方面我必須將它放在標題中,不是嗎? 或者我可以把它放在源文件的頂部?

我要說的是將范圍保持在最低限度; 有了它,做任何最干凈的事情。

如果將它用於一個函數,請將其保留在該函數的范圍內。 如果將它用於多個函數,請將其設置為私有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;
};

希望這可以讓你了解我的意思。

類范圍typedef非常好,它們不能與類范圍之外的任何東西沖突。

標准庫與類范圍typedef( value_typepointerreferenceiteratorconst_iterator等)合作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM