c – 了解模板部分专业化
发布时间:2020-12-16 09:53:52 所属栏目:百科 来源:网络整理
导读:我试图理解模板的部分特化的概念.但是我似乎把它与模板专业化混淆了.我正在考虑以下两个例子 template typename T struct test{ ///Some stuff};template //Specializationstruct testint*{ ///Some stuff};templatetypename t //Partial specializationstru
我试图理解模板的部分特化的概念.但是我似乎把它与模板专业化混淆了.我正在考虑以下两个例子
template <typename T> struct test { ///Some stuff }; template <> //Specialization struct test<int*> { ///Some stuff }; template<typename t> //Partial specialization struct test<t*> { ///Some stuff }; 我正在尝试以下方面 test<int*> s; 这会调用专门的模板.我怎样才能调用部分专业课程.有人可以用一个例子解释部分模板和专用模板之间的区别吗? 更新: 在完成答案后,我意识到只有当参数的一个子集需要专门化时,部分模板专业化才能提供帮助.所以我尝试过这样的事情 template <> struct test<int*> { }; //Partial Specialized template<typename t> struct test<t,std::string> { }; test<int*,std::string> s; //Error : Too many arguments for class template 这是为什么 ? 解决方法
简而言之,在谈论类模板时:
> Explicit (Full) Specialization :指定了所有模板参数 所有3个案例的例子: #include <iostream> template<typename T,typename U> //Primary template struct test { void foo() { std::cout << "nPrimary"; } }; template <typename T> //Specialization struct test<T,int*> { void foo() { std::cout << "nPartial Specialization"; } }; template<> //Full specialization struct test<int*,int*> { void foo() { std::cout << "nFull Specialization"; } }; int main() { test<int,double> t1; t1.foo(); test<double,int*> t2; t2.foo(); test<int*,int*> t3; t3.foo(); } 输出:
Live demo. 要回答您的更新: >模板特化无法添加参数,它只能专门化现有参数 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |