C ++部分模板特化语法 [英] C++ partial template specialization syntax

查看:164
本文介绍了C ++部分模板特化语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要范本:

  template< typename A,typename B>类模板专业化的类MyClass {... 

$ b之间的区别是什么
$ b

 模板< typename A,typename B> class MyClass< int,float> {... 

  template<> class MyClass< int,float> {... 


解决方案

;类型名A,类型名B> class MyClass< int,float> {... 应该不允许。事实上,如果你指定形式参数 A B ,你的模板应该使用它们。



第二种情况是正常的:你说你正在进行没有自由参数的专业化。



 模板< typename A> class MyClass< A,float> {... 

这也是有效的:这里你只修正第二个模板参数。 p>

部分专门化的想法如下:您使用一些形式参数创建一个模板,并使用它们来表达对初始模板的参数的约束。部分特化的参数不需要与初始模板参数相同。示例:

  template< typename X,typename Y,typename Z>类MyClass< X *,Y(Z&)> {... 

将是您案例的有效部分专业化。这可以读为对于任意类型 X Y Z ,如果 MyClass 的模板参数匹配 X * Y(Z& ),使用这个专业化。编译器应该非常聪明,以匹配类型模式。


for primary template:

template<typename A, typename B> class MyClass {...

with template specialization, what is the difference between

template<typename A, typename B> class MyClass<int, float> {...

and

template<> class MyClass<int, float> {...

解决方案

template<typename A, typename B> class MyClass<int, float> {... should be not allowed. Indeed, if you specify the formal parameters A and B, your template should be using them.

The second case is just normal: you say that you are making specialization with no "free" parameters.

An intermediate case could be

template<typename A> class MyClass<A, float> {...

which is again valid: here you are fixing only the 2nd template parameter.

The idea of a partial specialization is following: you make a template with some formal parameters, and use them to express the constraints on the parameters of initial template. The partial specialization's parameters don't need to be the same as the initial template parameters. Example:

template<typename X, typename Y, typename Z> class MyClass<X*, Y(Z&)> {...

would be a valid partial specialization for your case. This can be read as "for arbitrary types X, Y and Z, if MyClass's template parameters match X* and Y(Z&), use this specialization". Compiler should be quite clever in order to match the type pattern.

这篇关于C ++部分模板特化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆