我不确定您对发布的代码做了什么,但我确信它不会编译。我将尝试展示如何添加“一组函数并随机选择一个”。
int function1() { ... } // implementation is irrelevant
int function2(int x) { ... }
int function3(char x) { ... }
客户端代码:
#include <functional>
#include <vector>
std::vector<std::function<int(void)>> functions; // all functions placed
// in here take no parameters
functions.push_back(function1);
functions.push_back( []() { return function2(190); } ); // adaptor functor, calling
// function2 with parameters
// the adaptor matches the
// signature of
// functions::value_type
functions.push_back( []() { return function3('s'); } ); // same as above
从序列中调用一个随机函数:
#include <random>
std::random_device rd;
static std::mt19937 gen(rd()); // mersene twister
std::uniform_int_distribution<> d(0, functions.size());
auto itr = std::begin(functions);
std::advance(itr, dis(gen)); // advance iterator by random number of positions
(*itr)(); // call the functor
或:
#include <random>
std::random_device rd;
static std::mt19937 gen(rd()); // mersene twister
std::uniform_int_distribution<> d(0, functions.size());
auto index = dis(gen)); // get index in range [0, functions.size())
functions[index]();
为了保持代码干净,请考虑将响应函数放在命名空间中(至少):
namespace responses {
int function1() { ... } // implementation is irrelevant
int function2(int x) { ... }
int function3(char x) { ... }
}