C++跨文件调用模板函数提示undefined-reference

问题#

在一个基础头文件utils.h中定义了模板函数,在另一个工程中调用时编译报错undefined reference to ...

原因#

模板函数的特化必须在定义时完成,当模板函数和对应的调用在同一文件时,这一过程隐式发生。
而调用分离时生成的utils.o中不包含对应的特化函数符号,自然无法编译通过。

解决#

utils.cpp中实现函数后追加对应的特化方式

template <typename T>
bool_t function(const T& args)
{
    // ...
}
template bool_t function<A>(const A& args);
template bool_t function<B>(const B& args);




//举例====================<onnx_runtime_infer.cpp>===================



template  <typename  T>
bool    ONNX_RUNTIME_INFER::NetModel_Infer(const std::string &image_file, std::vector<T*> &out_data,\
                                           std::vector<std::vector<std::int64_t>> &out_dim, float vari_inv, float mean)
{
    cv::Mat  image = cv::imread(image_file);
    if(image.empty()){
        std::cout<<"Err:image is empty!"<<std::endl;
        return false;
    }
    return  NetModel_Infer<T>(image, out_data, out_dim, vari_inv, mean);
}


//在同一个cpp文件里(即函数的实现与实例化在一个.cpp),显示实例化
template
bool    ONNX_RUNTIME_INFER::NetModel_Infer<float>(const std::string &image_file, std::vector<float*> &out_data,\
                                           std::vector<std::vector<std::int64_t>> &out_dim, float vari_inv, float mean);
template
bool    ONNX_RUNTIME_INFER::NetModel_Infer<float>(const cv::Mat &input_image, std::vector<float*> &out_data,\
                                           std::vector<std::vector<std::int64_t>> &out_dim, float vari, float mean);


template
bool    ONNX_RUNTIME_INFER::NetModel_Infer<int64_t>(const std::string &image_file, std::vector<int64_t*> &out_data,\
                                           std::vector<std::vector<std::int64_t>> &out_dim, float vari_inv, float mean);
template
bool    ONNX_RUNTIME_INFER::NetModel_Infer<int64_t>(const cv::Mat &input_image, std::vector<int64_t*> &out_data,\
                                           std::vector<std::vector<std::int64_t>> &out_dim, float vari, float mean);









标签: none

评论已关闭