如何使用另一个文件中定义的函数打印当前文件名而不使用宏?

Pie*_*tro 12 c++ filenames inline

是否可以打印调用另一个文件中定义的函数的调用者源文件名,而无需__FILE__显式传递且无需使用预处理器技巧?

// Header.h

#include <iostream>
#include <string>
using namespace std;

void Log1(string msg) {
   cout << __FILE__ << msg << endl;   // this prints "Header.h"
}

void Log2(string file, string msg) {
   cout << file << msg << endl;
}

inline void Log3(string msg) {
   cout << __FILE__ << msg << endl;   // this prints "Header.h"
}


// Source.cpp

#include "Header.h"

int main()
{    
    Log1(" Test 1");
    Log2(__FILE__, " Test 2");
    Log3(" Test 3");
}
Run Code Online (Sandbox Code Playgroud)

通过这段代码,我得到的是:

pathTo\Header.h Test 1
pathTo\Source.cpp Test 2
pathTo\Header.h Test 3
Run Code Online (Sandbox Code Playgroud)

我本来期望最后一次调用打印:pathTo\Source.cpp Test 3

Ted*_*gmo 17

你可以使用std::source_location

// library.h
#pragma once
#include <source_location>
#include <string>

void Log(std::string msg, const std::source_location loc =
                                std::source_location::current());
Run Code Online (Sandbox Code Playgroud)
// library.cpp
#include "library.h"
#include <iostream>

void Log(std::string msg, const std::source_location loc) {
    std::cout << loc.file_name() << ' '<< msg << '\n';
}
Run Code Online (Sandbox Code Playgroud)
// Source.cpp
#include "library.h"

int main() {    
    Log("Test 1"); // Prints "Source.cpp Test 1"
}
Run Code Online (Sandbox Code Playgroud)

这需要 C++20。在 C++20 之前,您可以使用boost::source_location.

  • 哇,这样的魔法现在可以在 C++ 中实现了! (3认同)