如何用参数值调用函数(仅在运行时已知)
How to call a function(only known at runtime) with parameter values(only known at runtime)?
在运行时进行一次测试,以确定要调用两个函数中的哪一个,并确定参数值。
然后每隔几秒钟调用一次该函数。
void Foo::func( std::string s);
void Foo::func( std::string s1 std::string s2, std::string s2);
显然,每次调用测试(调用哪个函数(效率很低,尤其是当函数及其参数值一旦建立就不会改变时。
我需要这样的东西:
测试一次要调用的函数和已建立的参数值。
将初始化的函数分配给某种可调用变量。
funcVar = void Foo::func( "blah", "blah", "woof" );
或
funcVar = void Foo::func( "blah" );
然后调用函数;
for( every few seconds )
{
call FuncVar;
}
有什么可调用的变量可以用来做这件事吗?
您可以简单地使用lambda函数对象(闭包(,您可以随时调用它。
示例:
struct Foo
{
void func( std::string s){ std::cout << "single" << s << std::endl; };
void func( std::string s1, std::string s2, std::string s3)
{
std::cout << "tripple " << s1 << " " << s2 << " " << s3 << std::endl;
}
// Select which function to call
std::function<void()> Select( int what )
{
if ( what == 1 )
{
// Create a callable object and put in also parameters
return [this]() { func("Hallo"); };
}
else
{
// The same for the other selection
return [this]() { func("This","is","tripple!"); };
}
}
};
int main()
{
Foo foo;
// Pick what you want to select
auto action = foo.Select( 2 );
for ( ;; )
{
// and call it as often you like
action();
}
}
您可以使用std::bind
为两种用例创建一个具有存储参数和公共调用运算符的函子。检查这个片段:
#include <string>
#include <functional>
struct Foo {
static void a(std::string) {}
static void b(std::string, std::string) {}
};
int main() {
std::function<void()> x;
if(true) {
x = std::bind(&Foo::b, "a", "b");
}
x();
return 0;
}
如果要std::绑定重载函数,必须指定要使用的函数:
#include <string>
#include <functional>
#include <iostream>
#include <map>
struct Foo {
void b() { std::cout << name << ": function 1" << std::endl; }
void b(int i) {std::cout << name << ": function 2" << std::endl; }
std::string name;
};
void with_map() {
Foo f;
f.name = "with_map";
std::map<const int, std::function<void()>> map({
{10, std::bind<void(Foo::*)(), Foo&>(&Foo::b, f)},
{20, std::bind<void(Foo::*)(int), Foo&, int>(&Foo::b, f, 1)},
});
map[20]();
map[10]();
}
void without_map() {
Foo f;
f.name = "without_map";
std::function<void()> x = std::bind<void(Foo::*)(), Foo&>(&Foo::b, f);
x();
x = std::bind<void(Foo::*)(int), Foo&, int>(&Foo::b, f, 1);
x();
}
int main() {
without_map();
with_map();
return 0;
}
std::函数应该在这里工作。
std:: function<void()> fun = [&s] () {/* do work*/};
if (some_condition)
{
fun = [&s1,&s2,&s3] () {/* do your work*/} ;
}
if(every few seconds)
{
fun();
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 读取文件时运行时的未知行为
- 函数在Windows或Linux上运行时表现不同
- 在声明中合并两个常量"std::set"(不是在运行时)
- AWS Lambda C++运行时权限被拒绝
- 通过switch和static_cast访问多态对象的运行时类型
- 如何修复 Onnx运行时会话>运行问题?