考虑这段代码,我希望将Vec v
推导为Vec
的专业化模板。相反,我遇到了编译错误:
main.cpp: In function ‘int main()’:
main.cpp:25:9: error: class template argument deduction failed:
Vec v;
^
main.cpp:25:9: error: no matching function for call to ‘Vec()’
main.cpp:13:7: note: candidate: template Vec()-> Vec
class Vec{
^~~
main.cpp:13:7: note: template argument deduction/substitution failed:
main.cpp:25:9: note: couldn't deduce template parameter ‘T’
Vec v;
^
#include <iostream>
using namespace std;
template<class T, int N>
class Vec{
T _v[N];
};
template<>
class Vec<float, 4>{
float _v[4];
};
int main()
{
Vec v;
return 0;
}
您已经将专业化与默认模板参数混淆了。专业化用于编写函数/类的实现,以处理模板参数与某种模式匹配的特定情况。
这是您达到实际想要的方式:
template<class T = float, std::size_t N = 4>
class Vec
{
T _v[N];
};
int main()
{
Vec<> v;
}
对于这样的向量类,这可能没有意义。人们评论说,using Vec4f = Vec<float, 4>;
之类的词可能更合适。