c++ - 使用从字符串中提取的参数调用函数

标签 c++ parsing function reflection binding

我正在研究以下问题:

我得到的字符串格式如下:

functionname_parameter1_parameter2_parameter3
otherfunctionname_parameter1_parameter2
.
.
.

我想用给定的参数调用函数。 假设我有一个功能测试:

void test(int x, float y, std::string z) {}

然后我收到一条消息:

test_5_2.0_abc

然后我希望像这样自动调用函数测试:

test(5, 2.0, "abc");

关于如何在 C++ 中完成此操作,您有任何提示吗?

最佳答案

更新:更新了stream_function以解决@Nawaz 评论中提到的参数求值顺序问题,同时删除了std::function 以提高效率。 请注意,评估顺序修复仅适用于 Clang,因为 GCC 不遵循此处的标准。可以找到具有手动顺序执行的 GCC 示例 here .


这通常不是那么容易实现的。我曾经围绕 std::function 编写了一个小包装类,它从 std::istream 中提取参数。下面是一个使用 C++11 的示例:

#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <functional>
#include <stdexcept>
#include <type_traits>

// for proper evaluation of the stream extraction to the arguments
template<class R>
struct invoker{
  R result;
  template<class F, class... Args>
  invoker(F&& f, Args&&... args)
    : result(f(std::forward<Args>(args)...)) {}
};

template<>
struct invoker<void>{
  template<class F, class... Args>
  invoker(F&& f, Args&&... args)
  { f(std::forward<Args>(args)...); }
};

template<class F, class Sig>
struct stream_function_;

template<class F, class R, class... Args>
struct stream_function_<F, R(Args...)>{
  stream_function_(F f)
    : _f(f) {}

  void operator()(std::istream& args, std::string* out_opt) const{
    call(args, out_opt, std::is_void<R>());
  }

private:  
  template<class T>
  static T get(std::istream& args){
    T t; // must be default constructible
    if(!(args >> t)){
      args.clear();
      throw std::invalid_argument("invalid argument to stream_function");
    }
    return t;
  }

  // void return
  void call(std::istream& args, std::string*, std::true_type) const{
    invoker<void>{_f, get<Args>(args)...};
  }

  // non-void return
  void call(std::istream& args, std::string* out_opt, std::false_type) const{
    if(!out_opt) // no return wanted, redirect
      return call(args, nullptr, std::true_type());

    std::stringstream conv;
    if(!(conv << invoker<R>{_f, get<Args>(args)...}.result))
      throw std::runtime_error("bad return in stream_function");
    *out_opt = conv.str();
  }

  F _f;
};

template<class Sig, class F>
stream_function_<F, Sig> stream_function(F f){ return {f}; }

typedef std::function<void(std::istream&, std::string*)> func_type;
typedef std::map<std::string, func_type> dict_type;

void print(){
  std::cout << "print()\n";
}

int add(int a, int b){
  return a + b;
}

int sub(int a, int b){
  return a - b;
}

int main(){
  dict_type func_dict;
  func_dict["print"] = stream_function<void()>(print);
  func_dict["add"] = stream_function<int(int,int)>(add);
  func_dict["sub"] = stream_function<int(int,int)>(sub);

  for(;;){
    std::cout << "Which function should be called?\n";
    std::string tmp;
    std::cin >> tmp;
    auto it = func_dict.find(tmp);
    if(it == func_dict.end()){
      std::cout << "Invalid function '" << tmp << "'\n";
      continue;
    }
    tmp.clear();
    try{
      it->second(std::cin, &tmp);
    }catch(std::exception const& e){
      std::cout << "Error: '" << e.what() << "'\n";
      std::cin.ignore();
      continue;
    }
    std::cout << "Result: " << (tmp.empty()? "none" : tmp) << '\n';
  }
}

在 Clang 3.3 下编译并按预期工作 (small live example)。

Which function should be called?
a
Invalid function 'a'
Which function should be called?
add
2
d
Error: 'invalid argument to stream_function'
Which function should be called?
add
2
3
Result: 5
Which function should be called?
add 2 6
Result: 8
Which function should be called?
add 2   
6
Result: 8
Which function should be called?
sub 8 2
Result: 6

很高兴再次把那个类(class)聚在一起,希望你喜欢。请注意,您需要稍微修改代码才能为您的示例工作,因为 C++ IOstreams 将空格作为分隔符,因此您需要将消息中的所有下划线替换为空格。不过应该很容易做到,之后只需从您的消息构造一个 std::istringstream 即可:

std::istringstream input(message_without_underscores);
// call and pass 'input'

关于c++ - 使用从字符串中提取的参数调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8476975/

相关文章:

algorithm - 提高单词匹配(向前看?)算法性能

parsing - F# 解析器组合器

c++ - 如何使用 WinPcap 发送/注入(inject)数据包

c++ - QSharedPointer 和 QObject::deleteLater

java - 解析来自 Google map 页面的 JSON 响应

php - 数组大小写限制

php - 是否可以在 UML 中可视化一堆函数

c++ - 如何处理从 main 接收到的 NULL。 C++

c++ - qwt例子程序意外结束

c++ - 继承自QLabel的类,为什么不调用自定义槽?