【发布时间】:2011-12-08 02:52:47
【问题描述】:
我有以下代码:
typedef vector<int> Vec;
typedef vector<Vec> VecOfVec;
template<typename Vec>
Vec DoSomething(const Vec &v);
template<>
VecOfVec DoSomething<VecOfVec>(const VecOfVec &v)
{
VecOfVec r;
for(auto i = v.begin(); i != v.end(); i++)
r.push_back(DoSomething(*i));
return r;
}
template<>
Vec DoSomething<Vec>(const Vec &v) // Error here
{
return v; // for the sake of the example
}
我收到以下错误:
explicit specialization of 'DoSomething<vector<int> >' after instantiation
在标记线处。
编译器坚持认为它已经实例化了DoSomething<vector<int> >,但它不能,一个简单的程序可以证明这一点:
typedef vector<int> Vec;
typedef vector<Vec> VecOfVec;
template<typename Vec>
Vec DoSomething(const Vec &v);
template<>
VecOfVec DoSomething<VecOfVec>(const VecOfVec &v)
{
VecOfVec r;
for(auto i = v.begin(); i != v.end(); i++)
r.push_back(DoSomething(*i));
return r;
}
导致无法解决的外部问题。
为什么编译器说它已经实例化了它,而它不能甚至没有?为什么编译器不将其视为未解析的符号,而链接器却将其视为未解析的符号?
我知道切换方法顺序可以解决它,但我想知道编译器为什么要这样做。
【问题讨论】:
标签: c++ templates template-specialization