C++ Template specialization linker error

纵饮孤独 提交于 2019-12-13 02:36:37

问题


How can I separate header file from cpp file when I have template specialization ?

I have seen some posts on how to separate header from implementation for template by including cpp file at the end of header file. But this strategy does not work when I have to have template specialization.

here is my header file

#ifndef H_SUM_H
#define H_SUM_H

#include <map>
#include <string>

template <typename T>
double Sum(const T &source);

template <>
double Sum(const std::map<std::string, double> &source);

#ifndef CPP_SUM_CPP
#include "Sum.cpp"
#endif

#endif

and here is my implementation file

#ifndef CPP_SUM_CPP
#define CPP_SUM_CPP 
#include "Sum.h"

template <typename T>
double Sum(const T &source){//code//}

template <>
double Sum(const std::map<std::string, double> &source){//code//}

#endif

Two points :

1) If I remove the template specialization everything works well

2) When I include the cpp file (for the case with template specialization) the code

#ifndef CPP_SUM_CPP
#include "Sum.cpp"
#endif

is in grey color (in VC 2010) and is marked as a block code !!!

Any idea?

Thanks


回答1:


Your source file can only have template<>, nothing inside <>, functions/methods cannot be partially specialized. Generic types can only exist in header files.



来源:https://stackoverflow.com/questions/32292476/c-template-specialization-linker-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!