代码:
#include<iostream>
using namespace std;
struct S1{};
struct S2{};
struct S3{};
template<class T1>
class X
{
public:
template<class T2>
void print(T2 &v){};
};
template<class T1>
template<>
void X<T1>::print<S1>(S1 &v)
{
cout<<"S1"<<endl;
}
template<class T1>
template<>
void X<T1>::print<S2>(S2 &v)
{
cout<<"S2"<<endl;
}
template<class T1>
template<>
void X<T1>::print<S3>(S3 &v)
{
cout<<"S3"<<endl;
}
int main()
{
S1 s1;
S2 s2;
S3 s3;
X<int> x;
x.print(s1);
x.print(s2);
x;print(s3);
return(0);
}
编译失败,gcc:
$ g++ test_template.cpp
test_template.cpp:17:10: 错误:invalid explicit specialization before ‘>’ token
17 | template<>
| ^
test_template.cpp:17:10: 错误:所包含的类模板并未被显式特例化
test_template.cpp:25:10: 错误:invalid explicit specialization before ‘>’ token
25 | template<>
| ^
test_template.cpp:25:10: 错误:所包含的类模板并未被显式特例化
test_template.cpp:32:10: 错误:invalid explicit specialization before ‘>’ token
32 | template<>
| ^
test_template.cpp:32:10: 错误:所包含的类模板并未被显式特例化
test_template.cpp: 在函数‘int main()’中:
test_template.cpp:46:4: 错误:‘print’ was not declared in this scope; did you mean ‘printf’?
46 | x;print(s3);
| ^~~~~
--
FROM 183.197.153.*