1

I have a macro in a function that instantiates a variable of a given type (and does a couple of other things that are not relevant).

Essentially MACRO(foo, f) expands to foo f;

But if foo is say a std::map<int, int> then the expansion fails due to the extra comma.

I work around this by writing typedef std::map<int, int> bar; followed by MACRO(bar, b).

I'm concerned though that I'm leaking typedefs into the program source which may cause me problems in the future.

So, how long do typedefs last for?

  • 3
    You may find some use in reading about [The XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – jtbandes Dec 17 '15 at 09:50
  • Wait, so you are saying that `typedef std::map foo; MACRO(foo, f)` does not compile? I find that hard to believe. – CompuChip Dec 17 '15 at 09:52
  • btw "(and does a couple of other things that are not relevant)" is a quite common misconception. There is nothing irrelevant if it is related to the question. If your question involves a macro, then show us the macro (or a distilled version that shows same behavior with respect to the question), but please do not claim that it is not relevant. – 463035818_is_not_an_ai Dec 17 '15 at 09:52
  • No that does compile but MACRO(std::map, f) doesn't –  Dec 17 '15 at 09:53
  • Maybe you want to check out this question: http://stackoverflow.com/questions/13842468/comma-in-c-c-macro – CompuChip Dec 17 '15 at 09:56

2 Answers2

7

The rules for typedef availability are identical to those for a variable so in your case it will "last" as long as the function body.

You could have verified this yourself by writing

{typedef std::map<std::string, std::string, iLT> location_map;}

and observing the compiler errors: as soon as the scope block exists, the typedef itself is out of scope.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

typedef lasts until end of translation unit in global scope or namespace scope.

or end of scope when put inside an other scope.

Jarod42
  • 203,559
  • 14
  • 181
  • 302