【发布时间】:2014-05-13 16:01:42
【问题描述】:
是否可以为模板类型专门化模板函数?我不知道我的术语是否正确,所以我将提供一个简单的示例来说明我想要实现的目标:
#include <vector>
#include <string>
#include <iostream>
template<typename T>
void f()
{
std::cout << "generic" << std::endl;
}
template<>
void f<std::string>()
{
std::cout << "string" << std::endl;
}
template<typename T>
void f<std::vector<T>>()
{
std::cout << "vector" << std::endl;
}
int main()
{
f<double>();
f<std::string>();
f<std::vector<int>>();
return 0;
}
此代码无法编译。 VS2013给我
错误 C2995: 'void f(void)' : 函数模板已定义
关于这个功能:
template<typename T>
void f<std::vector<T>>()
{
std::cout << "vector" << std::endl;
}
我怎样才能实现这种行为?拥有type f(void) 签名非常重要。这段代码是否属于函数的部分特化(在 C++ 中是禁止的)?
【问题讨论】:
标签: c++ templates partial-specialization