问题
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