捕获函数名称
Capture function name
给定仅包含单个函数定义的任意 C++ 源代码,我尝试捕获函数的名称(可以是任意的)。
为此,我假设函数名称及其参数列表之间没有 symbols/words,即,我正在寻找第一次出现的括号符号“(
”(它启动函数的参数列表)并捕获它前面的单词(我认为它是函数的名称);这个程序正确吗?
不幸的是,我无法理解 C++ 规范(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf 第 207 页)。
函数 return 类型可能非常奇怪,例如
void foo(int t){}
void (* returnFptr())(int t){
return foo;
}
returnFptr()
的 return 类型是 void(*)(int)
。因此第一个左括号不能保证在函数名和参数列表之间。
I'm looking for the first occurrence of the bracket symbol "(" (which initiate the function's argument list) and capture the word in front of it (of which I think it is the function's name); is this proceeding correct?
不,这是不正确的。在最基本的情况下,这是真的:
int foo() {
return 1;
}
但是如果你想支持任何函数(非模板),那么在这种情况下它会失败:
std::function<int(int)> foo() {
return [](int) { return 1; };
}
检查 return 类型和函数名之间的空格也是一个坏主意,因为编译器会忽略大多数空格,即这会失败:
std::function< int ( int ) > foo( ) {
return [](int) { return 1; };
}
那么,你是怎么做到的呢? 您需要构建部分 C++ 解析器来分析函数定义。
你没办法支持every非模板函数,如果加上模板函数就更难了。 return类型可以包含任何字符,没有特殊的分隔符。
你也可以有函数指针,它是语言内置的,打破了下面的空格+括号搜索。您将需要构建一个解析器:(
为了简化,您可以禁止任何 #include
语句,这只会导致像第一个那样的基本功能。如果是这种情况,为什么不检查 (
符号并获取前面的单词,为什么不找到第一个空格并获取空格和 (
之间的所有内容?
std::string get_function_name(std::string source) {
auto whitespace = source.find(' ');
if (whitespace == std::string::npos)
return "";
auto open_bracket = source.find('(', whitespace); // find ( after whitespace
if (open_bracket == std::string::npos)
return "";
return source.substr(whitespace + 1, open_bracket - whitespace);
}
给定仅包含单个函数定义的任意 C++ 源代码,我尝试捕获函数的名称(可以是任意的)。
为此,我假设函数名称及其参数列表之间没有 symbols/words,即,我正在寻找第一次出现的括号符号“(
”(它启动函数的参数列表)并捕获它前面的单词(我认为它是函数的名称);这个程序正确吗?
不幸的是,我无法理解 C++ 规范(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf 第 207 页)。
函数 return 类型可能非常奇怪,例如
void foo(int t){}
void (* returnFptr())(int t){
return foo;
}
returnFptr()
的 return 类型是 void(*)(int)
。因此第一个左括号不能保证在函数名和参数列表之间。
I'm looking for the first occurrence of the bracket symbol "(" (which initiate the function's argument list) and capture the word in front of it (of which I think it is the function's name); is this proceeding correct?
不,这是不正确的。在最基本的情况下,这是真的:
int foo() {
return 1;
}
但是如果你想支持任何函数(非模板),那么在这种情况下它会失败:
std::function<int(int)> foo() {
return [](int) { return 1; };
}
检查 return 类型和函数名之间的空格也是一个坏主意,因为编译器会忽略大多数空格,即这会失败:
std::function< int ( int ) > foo( ) {
return [](int) { return 1; };
}
那么,你是怎么做到的呢? 您需要构建部分 C++ 解析器来分析函数定义。
你没办法支持every非模板函数,如果加上模板函数就更难了。 return类型可以包含任何字符,没有特殊的分隔符。
你也可以有函数指针,它是语言内置的,打破了下面的空格+括号搜索。您将需要构建一个解析器:(
为了简化,您可以禁止任何 #include
语句,这只会导致像第一个那样的基本功能。如果是这种情况,为什么不检查 (
符号并获取前面的单词,为什么不找到第一个空格并获取空格和 (
之间的所有内容?
std::string get_function_name(std::string source) {
auto whitespace = source.find(' ');
if (whitespace == std::string::npos)
return "";
auto open_bracket = source.find('(', whitespace); // find ( after whitespace
if (open_bracket == std::string::npos)
return "";
return source.substr(whitespace + 1, open_bracket - whitespace);
}