我想知道类模板和函数模板之间的区别,我应该在哪里使用它们。类模板和函数模板之间的区别
2
A
回答
4
实例化时,类模板成为类,函数模板成为函数。例子:
//Defines a template for a class that can hold two
//objects.
template<typename T1, typename T2>
struct pair {
T1 first;
T2 second;
};
//Defines a template for a function that gives the
//minimum of two values.
template<typename T>
T min(T a, T b) {
return a < b ? a : b;
}
对于普通的代码,你会当你想创建一个由类型参数化类和函数模板,当你想创建一个可以在许多不同的操作功能,使用类模板类型。
函数模板也能够做到型扣,其可以是用于创建工厂功能有用:
//Deduces the types of T1 and T2, so
//for example, a pair<int, double> can be created
//by `make_pair(10, 1.2)`
template<typename T1, typename T2>
pair<T1, T2> make_pair(T1&& t1, T2&& t2) {
return {std::forward<T1>(t1), std::forward<T2>(t2)};
}
类模板可以用来编写执行在编译时的程序(使用类型作为值,并将模板实例与模式匹配作为纯函数)。这方面的一个简单的例子是这组类模板从而消除从类型所有const
:
//Removes all `const` from a type, for example:
//`remove_const_recursive<int const*const volatile>::type`
//is the type `int*volatile`.
template<typename T> struct remove_const_recursive { typedef T type; };
template<typename T> struct remove_const_recursive<T const volatile> {
typedef typename remove_const_recursive<T>::type volatile type;
};
template<typename T> struct remove_const_recursive<T volatile> {
typedef typename remove_const_recursive<T>::type volatile type;
};
template<typename T> struct remove_const_recursive<T const> {
typedef typename remove_const_recursive<T>::type type;
};
template<typename T> struct remove_const_recursive<T&> {
typedef typename remove_const_recursive<T>::type& type;
};
template<typename T> struct remove_const_recursive<T*> {
typedef typename remove_const_recursive<T>::type* type;
};
当你使用模板越来越多,你会发现,他们可以在各种各样的方式来使用。 Expression templates允许您加快某些类型的代码或创建特定于域的语言。 Template metaprogramming和元组可以用来自动编写各种繁琐的代码。你也许会意识到模板的钝语法和有限的性能和语义能力意味着它们的成本并不总是被它们提供的好处所抵消。
1
函数模板试图从参数类型中推导出特化类型。
函数模板不能部分专用,而类可以。
函数模板在类可以使用时不能有默认的模板参数。
相关问题
- 1. wpf中控制模板和数据模板之间的区别
- 2. 模板include和jquery.load之间的区别?
- 3. 项目模板和版面模板之间的区别
- 4. 编辑器模板和显示模板之间的区别
- 5. 函数模板的区别
- 6. 函数模板和模板函数有什么区别?
- 7. .cpt模板和.pt模板之间有什么区别?
- 8. 指令与模板之间的区别与没有模板和Angular 1.2和1.1之间的区别?
- 9. Hibernate模板和JDBC模板的区别
- 10. 类模板+函数模板
- 11. 模板元编程时结构和类之间的区别
- 12. C++模板类和模板函数
- 13. C++:NVI和模板方法模式之间的区别?
- 14. 模板方法(分离)和策略模式之间的区别?
- 15. Meteor.js中的模板助手和模板变量之间的区别
- 16. 如何在类模板之外定义类模板的构造函数模板?
- 17. 自动扣除别名模板和模板类别的模板参数
- 18. 非模板类中的函数模板
- 19. 导出模板类的模板函数
- 20. 模板类中的模板函数
- 21. 模板类中的模板函数is_same
- 22. 接受模板类的模板函数
- 23. 模板类的专用模板函数
- 24. C模板仿函子。类模板vs函数模板
- 25. for-each和xsl中的模板之间的区别?
- 26. Grails中的视图和模板之间的区别
- 27. django模板标记中的formset和formset.forms之间的区别
- 28. 什么是产量和包含的模板之间的区别
- 29. C++模板的Class和Typename之间的区别
- 30. 函数模板的别名