【发布时间】:2018-08-09 12:49:08
【问题描述】:
#include <iostream>
#include <vector>
using namespace std;
class test
{
public:
template <typename T>
void f(const std::string& path, std::vector<T>& type_vec)
{
cout << "Base template ";
}
template <>
void f<std::string>(const std::string& path, std::vector<std::string>& type_vec)
{
cout << "Specialization vec ";
}
};
int main()
{
std::vector<int> vec_int;
std::vector<std::string> vec_str;
std::string path = "";
test T;
T.f(path, vec_int);
T.f(path, vec_str);
return 0;
}
得到以下编译错误:
main.cpp:24:15: error: explicit specialization in non-namespace scope 'class test'
template <>
^
main.cpp:25:84: error: template-id 'f' in declaration of primary template
void f<std::string>(const std::string& path, std::vector<std::string>& type_vec)
^
错误 1:有解决方法吗?非命名空间范围(本例中的类)是否完全不允许专门化?
错误 2:我知道函数模板的部分特化是不允许的。但是,我不知道这是部分专业化吗?有什么解决方法吗?
注意:如果函数不是类成员方法,代码编译正常。
【问题讨论】:
标签: c++ c++11 templates overloading template-specialization