- 论坛徽章:
- 0
|
恩,理解了,非常感谢 whyglinux 版主的耐心帮助!
最后写两段代码说明
- #include <iostream>
- using namespace std;
- template<typename T>
- void func (T &v1, T &v2) {
- cout<<"template"<<endl;
- }
-
- template<typename T>
- void func (const T &v1, const T &v2) {
- cout<<"template const"<<endl;
- }
-
- template <>
- void func<char [6]> ( char const (&v1)[6], char const (&v2)[6]) {
- cout<<"Specialization: char[6]"<<endl;
- }
- template <>
- void func<const char [6]> (char const(&v1)[6], char const(&v2)[6]) {
- cout<<"Specialization: const char[6]"<<endl;
- }
-
- int main()
- {
- const char * const p3 = "hello";
- const char * const p4 = "world";
- func(p3, p4);
-
- const char a3[6] = "hello";
- const char a4[6] = "world";
- func(a3, a4);
-
- return 0;
- }
复制代码
运行输出结果:
template const
Specialization: char[6]
注意:上面的代码中最后一个特化版本是第二个模板的特化,这个比较特殊,这也可以利用编译器验证:将最后一个特化重复定义可得到如下错误信息
main.cpp:25: error: redefinition of `void func(const T&, const T&) [with T = const char[6]]'
main.cpp:20: error: `void func(const T&, const T&) [with T = const char[6]]' previously declared here
另一段对比代码:
- #include <iostream>
- using namespace std;
- template<typename T>
- void func (T &v1, T &v2) {
- cout<<"template"<<endl;
- }
- template <>
- void func<const char [6]> (char const(&v1)[6], char const(&v2)[6]) {
- cout<<"Specialization: const char[6]"<<endl;
- }
-
- int main()
- {
- const char a3[6] = "hello";
- const char a4[6] = "world";
- func(a3, a4);
-
- return 0;
- }
复制代码
程序运行输出:
Specialization: const char[6]
今天下午去拿到了票,明天就上火车了,回家了,好高兴~~hoho |
|