显式实例化和显式具体化
大家好~!!
我在看 C++ Primer Plus ,作者在介绍函数模板的显式实例化和显式具体化的时候,有下面这样的一句话:
对句话不太理解,是不是不能像下面这样做?
template<typename T> //template
void foo(T t)
{
cout << t << endl;
return;
}
template void foo<double>(double); //Instantiation
template <> void foo<double>(double d) //Specialization
{
cout << "this is " << d << endl;
}
int main(int argv, char **argc)
{
foo(1.0);
return 0;
}
template<typename T> //template
void foo(T t)
{
cout << t << endl;
return;
}
template <> void foo<double>(double d) //Specialization
{
cout << "this is " << d << endl;
}
template void foo<double>(double); //Instantiation
int main(int argv, char **argc)
{
foo(1.0);
return 0;
}
根据这个说法,主楼的两种写法都是错误的,目测你 VS 的编译器执行的是旧标准。
c++11 14.7/5 说:
For a given template and a given set of template-arguments,
— an explicit instantiation definition shall appear at most once in a program,
— an explicit specialization shall be defined at most once in a program (according to 3.2), and
— both an explicit instantiation and a declaration of an explicit specialization shall not appear in a program unless the explicit instantiation follows a declaration of the explicit specialization.
An implementation is not required to diagnose a violation of this rule.
根据这种定义,主楼第一种写法不满足第三条 unless 给出的条件,所以是错误;但是第二种写法则能够满足,所以编译无误,目测你的 g++ 编译器是按照新标准解释的。
另外,在 explicit specialization 和 explicit instantiation 同时存在的情况下,后者没有作用。
[解决办法]