[英]c++ Function pointer returned based on template string literal
How can i return a function object based on a string literal argument? 我如何基于字符串文字参数返回函数对象?
This argument need not be a template, but I want to be able to input a string literal and return a function object 此参数不必是模板,但我希望能够输入字符串文字并返回函数对象
Im looking for something like: 我正在寻找类似的东西:
template<const char * s> func_pointer(int arg);
I have tried returning a lambda. 我试图返回一个lambda。 I have also tried returning a class operator() and a templated function. 我也尝试过返回一个类operator()和一个模板函数。 None work. 没有工作。
Any help is appreciated! 任何帮助表示赞赏!
EDIT: calling the function with an extern variable
will not work for my purposes either. 编辑:调用带有extern variable
的函数对我来说也不起作用。
EDIT: I am writing a language parser. 编辑:我正在写一个语言解析器。 I want to build framework for the parser to avoid rewriting a lot of code. 我想为解析器构建框架,以避免重写大量代码。 Therefore, I want to be able to have a bunch of functions that parse the text. 因此,我希望能够拥有一堆解析文本的函数。 I want to have a base function that parses a single string literal (the program is lexed.), and I want to be able to pass in the string for each possible base function. 我想拥有一个解析单个字符串文字(程序被词法化)的基本函数,并且我希望能够为每个可能的基本函数传递字符串。
EDIT: Note that any function object that can convert a lambda and a function pointer to a generalized type(like std::function) will do. 编辑:请注意,任何可以将lambda和函数指针转换为通用类型(如std :: function)的函数对象都可以。
For me one of the easiest ways to map a string to a function is a map<string, function<int(int)>
. 对我来说,将字符串映射到函数的最简单方法之一是map<string, function<int(int)>
。 Here's a simple example: 这是一个简单的例子:
#include <string>
#include <iostream>
#include <functional>
#include <map>
int add(int a, int b){return a+b;}
int subtract(int a, int b){return a-b;}
int multiply(int a, int b){return a*b;}
int divide(int a, int b){return (b!=0?a/b: -1);}
map<string, function<int(int,int)>> functions =
{
{"add",add},
{"subtract",subtract},
{"multiply",multiply},
{"divide",divide}
};
int main(int argc, char** argv)
{
cout << functions["add"](5,2);
return 0;
}
What I was looking for is the std::function object ( thanks to @tinstaafl ), this way I can have lambdas and function pointers convertible to te same type. 我正在寻找的是std :: function对象(感谢@tinstaafl),这样我就可以将lambda和函数指针转换为相同类型。 A function can return a lambda based on a string literal. 函数可以基于字符串文字返回lambda。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.