Is it bad practice to declare a typedef at class scope? 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?
Classes and structures can have nested typedefs declared within them.
No. Not when used appropriately. I haven't heard anyone say typedefs are bad in general. It would be great if typedefs in C++ can do more (having typedefs actually create new types), but it's still better than nothing.
@KitsuneYMG: Yes.
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
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. 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.
The standard library is teaming with class scope typedefs (value_type
, pointer
, reference
, iterator
, const_iterator
etc etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With