模板参数推导和函数参考

时间:2018-11-17 14:12:10

标签: c++ c++11 templates

我遇到了一个间接调用功能模板实例的问题。下面的结构定义了间接传递的参数类型(以下所有代码都属于一个.hpp文件):

template<typename individual, typename fitness_value>
struct global_model_worker_state: public base_state {

global_model_worker_state(
        const global_model_worker_state<individual, fitness_value>&) = default;

global_model_worker_state(const shared_props& props,
        const fitness_evaluation_operator<individual, fitness_value>& feo) :
        base_state { props }, fitness_evaluation { feo } {
}

global_model_worker_state& operator=(
        const global_model_worker_state<individual, fitness_value>&) = default;

global_model_worker_state& operator=(
        global_model_worker_state<individual, fitness_value>&&) = default;

fitness_evaluation_operator<individual, fitness_value> fitness_evaluation;
};

无法解析引用的函数:

template<typename individual, typename fitness_value>
behavior global_model_worker(
        stateful_actor<global_model_worker_state<individual, fitness_value>>* self,
        global_model_worker_state<individual, fitness_value> state) {
    self->state = std::move(state);

    return {
        [=](compute_fitness, const individual& ind) {
            // Undefined reference
            return self->state.fitness_evaluation(ind);
        },
    };
}

然后我继续调用spawn,该方法接受函数引用以及转发给函数的任意数量的参数。

template<typename individual, typename fitness_value>
void run() {
     ...
     self->spawn(
             global_model_worker<individual, fitness_value>,
             global_model_worker_state<individual, fitness_value> {
                     self->state.props, feo 
             });
 }

然后在.cpp文件中:

 run<std::vector<bool>, int>();

链接器返回的错误消息是undefined reference to Common::genetic_operator<int, std::vector<bool, std::allocator<bool> > const&>::operator()(std::vector<bool, std::allocator<bool> > const&),它是类模板genetic_operator<individual, fitness_value>(其中fitness_evaluation_operator是别名)的实例。

我无法编译此代码,因为(大概)无法通过fitness_evaluation的间接调用方式(编译器不知道)来推断global_model_worker<individual, fitness_value>的具体类型。我的问题是,有没有办法建议绕过这个问题?

0 个答案:

没有答案