在类范围声明typedef是不好的做法吗?为每个函数声明它们以确保没有人包含该文件然后创建具有相同名称的东西更好吗?
例如
typedef std::vector<int>::size_type vec_int;
在我的一些标题中会有用,因为在某些类中有许多使用此类型的函数,但另一方面我必须将它放在标题中,不是吗?或者我可以把它放在源文件的顶部吗?
答案 0 :(得分:14)
我要说的是将范围保持在最低限度;有了它,做任何最干净的事。
如果将它用于一个功能,请将其保留在该功能的范围内。如果将它用于多个函数,请将其设置为私有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;
};
希望这可以让你了解我的意思。
答案 1 :(得分:11)
类范围typedef非常好,它们不能与类范围之外的任何东西发生冲突。
标准库正在与类范围typedef(value_type
,pointer
,reference
,iterator
,const_iterator
等进行合作。