【问题标题】:operator[] caller's site source location current workaroundoperator[] 调用者的站点源位置当前解决方法
【发布时间】: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


【解决方案1】:

找到解决办法:

#include <iostream>
#include <string>
#include <source_location>
#include <string_view>
#include <concepts>

struct string_like
{
  std::string_view strView;
  std::source_location s;
    
  template <typename T>
  string_like (T strView, std::source_location s = std::source_location::current())
    requires std::constructible_from<std::string_view, T>
    : strView(strView), s(s) {}
};

struct Test
{
  auto operator[](string_like s)
  {
    return s.s;
  }
};

int main()
{
  auto t = Test {};
  auto s0 = t["hello"];
 
  // prints main.cpp:29 as it should
  std::cout << s0.line() << ' ' << s0.function_name() << '\n';
}

【讨论】:

  • 这与下标运算符的通常行为大相径庭。不知道你打算用它做什么,但它可能会很有趣。
  • 它用于调试中使用的日志记录目的。 std::map 周围的小包装器抛出异常并打印使用 operator[] 访问未初始化值的信息
  • 我很确定这将是一次错误搜寻。无法在实验室的调试版本中重现问题?调试器和断点可以更轻松地进行精确定位。
  • 我什么也没找到。我不得不停止寻找,但this 建议您保持一致性并且有一个规则。我就是找不到。
  • 找到了。它真的很小:eel.is/c++draft/dcl.fct.default#2 声明等效的高亮末尾的那一点点。
猜你喜欢
  • 2012-07-07
  • 2023-03-19
  • 1970-01-01
  • 2015-02-14
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
相关资源
最近更新 更多