Skip to content

Instantly share code, notes, and snippets.

@modeco80
Created September 11, 2020 06:34
Show Gist options
  • Save modeco80/fba7325c6e3c663f1eda16dc4200e30b to your computer and use it in GitHub Desktop.
Save modeco80/fba7325c6e3c663f1eda16dc4200e30b to your computer and use it in GitHub Desktop.
std::source_location polyfill for C++17(and C++14, but please!) compilers
// std::source_location polyfill for C++17(and C++14, but please!) compilers.
//
// This polyfill does deviate a bit from the standard, as there is no consteval,
// but besides that, it should be nearly drop in replacement from this -> C++20.
//
// License details:
// Use this however you like.
// REQUIREMENTS:
// Your compiler must have the follwing intrinsic functions:
//
// __builtin_FILE()
// __builtin_LINE()
// __builtin_FUNCTION()
//
// On MSVC, you also need __builtin_COLUMN().
namespace std {
struct source_location {
static constexpr source_location current(
const unsigned int line = __builtin_LINE(),
#ifdef _MSC_VER
// MSVC helpfully provides the __builtin_COLUMN() intrinisic.
const unsigned int column = __builtin_COLUMN(),
#else
const unsigned int column = 0,
#endif
const char* filename = __builtin_FILE(),
const char* function_name = __builtin_FUNCTION()) noexcept {
source_location loc {};
loc._filename = filename;
loc._function_name = function_name;
loc._line = line;
loc._column = column;
return loc;
}
constexpr unsigned int line() const noexcept {
return _line;
}
constexpr unsigned int column() const noexcept {
return _column;
}
constexpr const char* file_name() const noexcept {
return _filename;
}
constexpr const char* function_name() const noexcept {
return _function_name;
}
private:
unsigned int _line;
unsigned int _column;
const char* _filename;
const char* _function_name;
};
} // namespace std
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment