是否可以为模板类型特化一个模板函数?我不知道我的术语是否正确,所以我将提供一个简单的示例来说明我想要实现的目标:
#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 给我
error C2995: 'void f(void)' : function template has already been defined
关于这个函数:
template<typename T>
void f<std::vector<T>>()
{
std::cout << "vector" << std::endl;
}
我怎样才能实现这种行为?拥有type f(void)
签名非常重要。此代码是否属于函数的部分特化(在 C++ 中禁止)?
最佳答案
你不能部分特化模板函数,但你可以部分特化模板类。 所以你可以将你的实现转发给一个专门的类。 以下内容可能有所帮助:( https://ideone.com/2V39Ik )
namespace details
{
template <typename T>
struct f_caller
{
static void f() { std::cout << "generic" << std::endl; }
};
template<>
struct f_caller<std::string>
{
static void f() { std::cout << "string" << std::endl; }
};
template<typename T>
struct f_caller<std::vector<T>>
{
static void f() { std::cout << "vector" << std::endl; }
};
}
template<typename T>
void f()
{
details::f_caller<T>::f();
}
关于c++ - 如何使用模板类型专门化模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22810293/