简体   繁体   English

函数模板显式特化c ++

[英]Function template explicit specialization c++

My book mentions two ways for explicit specialization: 我的书中提到了两种明确专业化的方法:

template <> void Swap<int> (int &, int &);
template <> void Swap(int &, int&);

what is the difference between both? 两者有什么区别? when to use one and when to use the other? 什么时候使用另一个?何时使用另一个? what is exactly the <> after the function name? 函数名后面的<>是什么?

what is the difference between both? 两者有什么区别?

There is no difference . 没有区别

In the second case, you are letting the compiler perform type deduction from the signature of the specialization. 在第二种情况下,您要让编译器从特化的签名中执行类型推导 Therefore, both forms declare a specialization of Swap<T>() for T = int . 因此,两种形式都为T = int声明了Swap<T>()的特化。

when to use one and when to use the other? 什么时候使用另一个?何时使用另一个?

At your discretion, when one form or the other meets your requirements in terms of readability or ease of maintenance. 在您的可读性或易维护性方面,当一种形式或另一种形式满足您的要求时,您可以自行决定。

what is exactly the <> after the function name? 函数名后面的<>是什么?

When it comes after the function name , it is the syntax for specifying template arguments: 当它出现在函数名之后 ,它是指定模板参数的语法:

template<typename T = double, typename U = char>
void foo();

foo<int, bool>(); // Specifies explicit template arguments
foo<>(); // Use default template arguments
foo(); // Same as above, allowed for *function* templates only

When it comes after the template keyword , it is the syntax for introducing a (class or function) template specialization. 当它出现 template 关键字之后时 ,它是引入(类或函数)模板特化的语法。

The first example is the real way to explicitly specialize a template, the second example is just a shortcut for the first way since the compiler can deduced the type itself from the function signature. 第一个示例是显式专门化模板的真正方法,第二个示例只是第一种方式的快捷方式,因为编译器可以从函数签名中推断出类型本身。 The result is the same , there is no real difference. 结果是一样的 ,没有真正的区别。

The <> is used to give the template parameter to a templated structure, in this case the template parameter is the type of the manipulated data and the specialization is for the type int . <>用于将模板参数提供给模板化结构,在这种情况下,模板参数是操纵数据的类型,专门化是类型int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM