以下代码在 gcc 4.5.3 上编译失败
struct Frobnigator
{
template<typename T>
void foo();
template<typename T>
void bar();
};
template<typename T>
void Frobnigator::bar()
{
}
template<typename T>
void Frobnigator::foo()
{
bar<T>();
}
template<> // error
void Frobnigator::foo<bool>()
{
bar<bool>();
}
template<>
void Frobnigator::bar<bool>()
{
}
int main()
{
}
错误信息:specialization of ‘void Frobnigator::bar() [with T = bool]’ after instantiation
.我终于通过 Frobnigator::bar<bool>()
的特化解决了这个问题。出现在 Frobnigator::foo<bool>()
之前.显然,方法出现的顺序很重要。
那为什么是上面代码的以下精简版,其中bar
的特化出现在通用版本之后,有效吗?
struct Frobnigator
{
template<typename T>
void foo();
};
template<typename T>
void Frobnigator::bar()
{
}
template<>
void Frobnigator::bar<bool>()
{
}
int main()
{
}
最佳答案
您的第一个代码按标准不正确。
n3376 14.7.3/6
If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.
在您的情况下 - bar
的隐式实例化类型为 bool
的函数在 foo<bool>
中的用法需要它, 在显式特化声明之前。
关于c++ - 实例化错误后成员函数模板的特化,以及成员函数的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112148/