Let's say I have a namespace my and this namespace contains a class foo.

What should I prefer nesting typedefs into my class or hold it in my namespace?

namespace my {

class foo {
  // some stuff

  // nested one
  typedef bar my_foo_bar;


// or namespaced one
typedef bar my_foo_bar;


Looking at the std-libs most things are the namespace variant.

(maybe a bad example but...) istream is not nested in iostream (at this point I only mean the way of using -> std::fstream, std::istream, ...), so I can use it directly. but also the list of possible functions is quite huge in std::

I could do both. The first variant is more encapsulated but also if I have to much inheritance I have to type a lot (my::foo::inh::and::so::on) if I won't use using [namespace].

First I thought the nested variant is more nice because of the encapsulation of what I want to have in the same "group". I also could do a new namespace inside my, but then I have also to type every time the new namespace (also without using [namespace]).

  • 2
    Relevant: stackoverflow.com/q/759512/10468
    – DarenW
    Commented Sep 11, 2013 at 23:48
  • istream is not nested in iostream obviously because iostream is a subclass of istream! That definitely isn't good example.
    – Jan Hudec
    Commented Sep 12, 2013 at 7:40

1 Answer 1


I think that your choice here depends a lot on context.

As a general set of guidelines, I'd say, in rough decreasing order of importance:

  • you write your code once, and read it one or more times. What do you plan to do with your type? What kind of code will you likely have to write, including it? Optimize for maximum legibility, most of the time.
  • generally, it's better to use the most restricted possible name-space for your typedef. So, if you're only using it inside the class, define it there. If you're looking to access it from other places, that have access to the namespace, leave it outside of the class
  • as a heuristic, in my own work, I find myself placing the typedefs in classes more often than not. So if I'm not entirely sure and under pressure to decide quickly, I start by placing the typedef in the class, and refactor it out if I turn out to be wrong. For you, you can look at surrounding code and copy their decision, for now, if you're in a hurry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.