如何打印作为参数传递的函数的名称
How to print the name of function passed as an argument?
在下面的代码中,我希望Benckmark
打印传递到Benchmark
的函子的名称。
#include<iostream>
using namespace std;
// You can only modify Benchmark
template<typename F>
void Benchmark(F f)
{
f();
// print the name to which f() refers.
}
// A cannot be modified
void A(int x)
{
}
void main()
{
int x = 1;
Benchmark([&]() {A(x); }); // should only print "A" rather than "[&]() {A(x); }"
}
C++中没有办法进行这种反思(无论如何,在撰写本文时(。你能做的最好的事情是使用包装宏,它获取你传递的令牌序列,从中创建一个字符串,并将其与一些更有用的数据一起传递给真正的函数。
#define Benchmark(...) BenchmarkImpl(__VA_ARGS__, #__VA_ARGS__, __FILE__, __LINE__)
template<typename F>
void BenchmarkImpl(F f, char const* name, char const* file, unsigned long long line)
{
f();
std::cout << "ran " << name << "(" << file << ", line " << line << " )";
}
在魔杖盒上运行上面的代码,打印:
ran [&]() {A(); } (prog.cc, line 19 )
使用 MACRO,您可以执行一些操作:
template<typename F>
void Benchmark(const char* name, F f)
{
std::cout << name << std::endl;
f();
}
#define BENCHMARK(f) Benchmark(#f, [](){ f; })
void A()
{
//
}
int main()
{
BENCHMARK(A());
}
在@TellStory的答案中添加修剪内容。
#include <regex>
#include <iostream>
using namespace std;
#define Benchmark(...) BenchmarkImpl(__VA_ARGS__, #__VA_ARGS__)
template<typename F>
void BenchmarkImpl(F f, char const* name)
{
const string input = name;
const regex regex("\{\s*(\w+)\s*\(");
smatch match;
string output = "defaultName";
if (regex_search(input, match, regex))
output = match.str(1);
f();
cout << "Function name: " << output << endl;
}
void Ab1(int x)
{
//
}
int main()
{
int x = 10;
Benchmark([&]() { Ab1 (x); });
}
C++没有
类型反射,但有一个解决方法。不优雅,但有效。
#include <iostream>
using namespace std;
typedef void (*FunctionType)();
template<typename F>
void Benchmark(F f)
{
f();
}
#define BENCHMARKTEST(F, f)
cout << "Benchmark test for:" << #f << endl;
Benchmark<F>(f);
void funcToBeTest()
{
}
int main()
{
BENCHMARKTEST(FunctionType, funcToBeTest);
return 0;
}
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 如何传递带有通过引用传递的结构参数的函数?
- 如何在 c++ 中将函数作为参数传递?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将函数作为参数传递以避免重复代码
- 如何在类(C )中作为参数传递函数