从命名空间获取具有相同签名的函数,并在C ++中迭代它们

时间:2017-08-06 12:57:07

标签: c++ c++14

我得到了一个(可能)无限的具有相同签名的函数集,这些函数都位于相同的命名空间中:

namespace cost_functions
{
   int calculate_cost_1(std::vector<double> waypoints, double time);
   int calculate_cost_2(std::vector<double> waypoints, double time);
   ...
   int calculate_cost_n(std::vector<double> waypoints, double time);
}

我希望动态地将这些函数放入向量中,这样我就可以通过以下方式迭代它们:

auto waypoints = get_waypoints();
auto t = get_time();
auto cost_functions = get_all_cost_functions();
auto total_cost = 0;
for(cost_function:cost_functions)
{
   total_cost += cost_function();
}

我如何实施get_all_cost_functions()?在C ++ 14中有某种反思吗?

1 个答案:

答案 0 :(得分:3)

  

C ++ 14中有某种反思吗?

没有反思。

  

如何实施get_all_cost_functions()

的内容
const std::vector<std::function<int (std::vector<double>,double)>>& 
    get_all_cost_functions() {
        static std::vector<std::function<int (std::vector<double>,double)>> funcs {
            calculate_cost_1 ,
            calculate_cost_2 ,
            calculate_cost_3 ,
            calculate_cost_4 ,
            calculate_cost_5 ,
            calculate_cost_6 ,
            // 
            calculate_cost_xx ,
            };
        return funcs;
    }

这是另一个想法(可能在将来添加额外的成本计算功能时更容易管理):

#include <iostream>
#include <functional>
#include <vector>

namespace cost_functions
{

    class CostFunctionRegistrar {
    public:
    typedef std::function<int (std::vector<double>,double)> CostCalulationFunc;

         CostFunctionRegistrar(std::function<int (std::vector<double>,double)> func) {
             allCostCalculationFuncs.push_back(func);
         }
         static const std::vector<CostCalulationFunc>& get_all_cost_functions() {
             return allCostCalculationFuncs;
         }
    private:
         static std::vector<CostCalulationFunc> allCostCalculationFuncs;
    };

    std::vector<CostFunctionRegistrar::CostCalulationFunc> CostFunctionRegistrar::allCostCalculationFuncs;

   int calculate_cost_1(std::vector<double> waypoints, double time) {
       std::cout << "calculate_cost_1" << std::endl;
       return 0;
   }
   static CostFunctionRegistrar r1(calculate_cost_1);

   int calculate_cost_2(std::vector<double> waypoints, double time) {
       std::cout << "calculate_cost_2" << std::endl;
       return 0;
   }
   static CostFunctionRegistrar r2(calculate_cost_2);

   int calculate_cost_n(std::vector<double> waypoints, double time) {
       std::cout << "calculate_cost_n" << std::endl;
       return 0;
   }
   static CostFunctionRegistrar rn(calculate_cost_n);
}


int main()
{
    for(auto cost_calc : cost_functions::CostFunctionRegistrar::get_all_cost_functions()) {
        std::vector<double> waypoints;
        double time = 0;
        cost_calc(waypoints,time);
    }
}

查看实时演示工作here