【发布时间】:2021-11-18 03:44:47
【问题描述】:
遗憾的是,当前的源位置不能直接在 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';
}
【问题讨论】:
-
这有X-Y Problem 的味道。什么现实世界的问题导致你找到这个可能的解决方案?我们无法帮助您解决您提出的问题,但我们或许可以帮助您解决导致该问题的问题。
-
因为我想获取运营商的调用者的源位置。同时我找到了解决方案。
-
时髦。我想看看你的想法,所以请自行回答。
-
做到了。它肯定是某种肮脏的,但它会完成它的工作
-
只需让
operator[]()通过 const 引用接受某个类/结构类型的参数。该类将需要一个构造函数,该构造函数接受(例如)int索引作为第一个参数,std::source_location()作为第二个参数,默认为std::source_location::current()。然后operator[]()可以根据需要检索索引和源位置。
标签: c++ operator-overloading subscript-operator std-source-location