4

There are some predefined preprocessor macros (specified in C and C++ standard) like __line__ and __file__ which are replaced by line number and file name during preprocessing respectively. In C++20, a new class std::source_location is introduced which does more or less the same thing.

So, my questions are...

  • What are the differences between them?
  • What are their advantages and disadvantages?
  • Which one I should use for which reason?
Akib Azmain Turja
  • 1,142
  • 7
  • 27
  • As stated on [cpp reference](https://en.cppreference.com/w/cpp/utility/source_location), "It is intended that source_location has a small size and can be copied efficiently. – Tom Sep 01 '20 at 07:41
  • One difference is that with `std::source_location` objects you no longer need "ugly" macros for many things, you can use simple functions (as shown in e.g. [this example](https://en.cppreference.com/w/cpp/utility/source_location#Example)). – Some programmer dude Sep 01 '20 at 07:44

1 Answers1

4

Preprocessor macros live outside the type system. Preprocessor macro substitution happens outside the rest of the language. See this answer and this answer for a comprehensive discussion of the disadvantages of using the preprocessor.

std::source_location on the other hand behaves like any other C++ struct. It has plain value fields that are typed and behave like any other values in the language.

Besides that, functionality-wise the two mechanisms are equivalent. There is nothing that the one can achieve that cannot be done by the other (apart from the column field in source_location, which has no equivalent in the preprocessor). It's just that the new approach achieves its goals more nicely.

Akib Azmain Turja
  • 1,142
  • 7
  • 27
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • 1
    You cannot paste `source_location` line with another token. With `__LINE__` it is a way to create unique identifiers. – n. m. could be an AI Sep 01 '20 at 07:56
  • @n.'pronouns'm.: There are way to create unique identifier without MACRO.(template taking type with lambda) – Jarod42 Sep 02 '20 at 12:37
  • 1
    @Jarod42 That would not be an identifier ;) It works 99% of the time, but you cannot create an enum this way for example. There are probably other ways to achieve any particular result though. – n. m. could be an AI Sep 02 '20 at 13:51