简体   繁体   English

类范围typedef不好的做法?

[英]Class scope typedef bad practice?

Is it bad practice to declare a typedef at class scope? 在类范围声明typedef是不好的做法吗? Is it better to declare them for every function to make sure no one includes that file and then creates something with the same name? 为每个函数声明它们以确保没有人包含该文件然后创建具有相同名称的东西更好吗?

For example 例如

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

Would be useful in some of my headers as in some classes there are many functions that use this type, but on the other hand I would have to put it in the header, wouldn't I? 在我的一些标题中会有用,因为在某些类中有许多使用此类型的函数,但另一方面我必须将它放在标题中,不是吗? Or could I put it at the top of the source file? 或者我可以把它放在源文件的顶部?

I'd say just keep the scope to a minimum; 我要说的是将范围保持在最低限度; with that, do whatever is cleanest. 有了它,做任何最干净的事情。

If you use it for one function, keep it in that function's scope. 如果将它用于一个函数,请将其保留在该函数的范围内。 If you use it for several functions, make it a private typedef. 如果将它用于多个函数,请将其设置为私有typedef。 And if you expect others to use it (out of utility, perhaps), make it public. 如果您希望其他人使用它(可能不是实用程序),请将其公之于众。

In code: 在代码中:

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;
};

Hopefully that gives you an idea of what I mean. 希望这可以让你了解我的意思。

Class scope typedefs are perfectly fine, and they can't conflict with anything outside the class scope. 类范围typedef非常好,它们不能与类范围之外的任何东西冲突。

The standard library is teaming with class scope typedefs ( value_type , pointer , reference , iterator , const_iterator etc etc). 标准库与类范围typedef( value_typepointerreferenceiteratorconst_iterator等)合作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM