2011-11-28 56 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等等等等)分组。