遗憾的是,当前源位置不能直接在 operator[] 的参数列表中使用,因为该运算符必须只有一个参数。但是,是否有解决方法,以便我可以获取调用者源代码行?例如,考虑以下代码:
#include <iostream>
#include <string>
#include <source_location>
struct Test
{
std::source_location src_clone(std::source_location a = std::source_location::current())
{
return a;
}
//this doesnt work:
//auto operator[](int a, std::source_location src_clone = std::source_location::current())
auto operator[](int a)
{
return std::source_location::current();
}
};
int main()
{
auto t = Test{};
auto s1 = t.src_clone();
std::cout << s1.line() << ' ' << s1.function_name() << '\n';
// is there a way to make this print "main.cpp:30"?
auto s0 = t[5];
std::cout << s0.line() << ' ' << s0.function_name() << '\n';
}