C++ 模板特化链接器错误

标签 c++ templates specialization

当我有模板特化时,如何将头文件与 cpp 文件分开?

我看过一些关于如何通过在头文件末尾包含 cpp 文件来将头文件与模板实现分开的帖子。但是当我必须进行模板特化时,这种策略就不起作用了。

这是我的头文件

#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

这是我的实现文件

#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

两点:

1) 如果我删除模板特化,一切正常

2) 当我包含 cpp 文件时(对于模板特化的情况)代码

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

为灰色(在 VC 2010 中)并标记为 block 代码!

有什么想法吗?

谢谢

最佳答案

你的源文件只能有template<> ,里面什么都没有 <> , 函数/方法不能部分特化。通用类型只能存在于头文件中。

关于C++ 模板特化链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32292476/

相关文章:

c++ - 模板类作为STL容器参数

c++ - 使用部分模板类作为专门的模板函数

c++ - 专门化可变参数模板的返回类型

c++ - 为什么重命名我的变量可以防止段错误?

c++ - 传递指向结构的引用作为模板参数

c# - "Cartiesian Product"C++ 方法

c++ - 矩阵模板类通过常量引用传递参数

windows - Windows 7 上的 Perl 5.16 无法安装模板工具包

c++ - 这是否完美地模仿了函数模板特化?

c++ - 伪造/模拟非虚拟 C++ 方法