C++26引入了一些新的特殊函数,这些函数在作为默认参数时,可以查询调用位置,类似于std::source_location::current()。使用这些函数之一,例如std::meta::current_function,可以获取并检查调用者函数的反射。这使得通过函数参数和注解实现基本的函数着色成为可能。虽然我看不到立即的实际用途,但我认为这很酷,因此想分享这个概念验证。
#include <iostream>
#include <source_location>
void example_function(const std::source_location location = std::source_location::current()) {
std::cout << "Called from: " << location.file_name() << " at line " << location.line() << '\n';
}
int main() {
example_function(); // Outputs the call location
return 0;
}
博主点评: C++26的新特性为函数的反射和调用位置查询提供了强大的支持,这不仅提升了调试的便利性,也为未来的代码分析工具奠定了基础。尽管当前看似用途有限,但其潜力值得关注。