关于C ++模板的最重要的事情...教训 [英] Most important things about C++ templates… lesson learned

查看:83
本文介绍了关于C ++模板的最重要的事情...教训的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于模板最重要的事情是什么:隐藏的功能,常见的错误,最好的和最有用的做法,提示... 常见的错误/疏忽/假设



我开始使用模板实现我的大部分库/ API,并希望收集实践中发现的大多数常见模式,提示等。



让我正式说明这个问题:你学到的关于模板的最重要的东西是什么?



请尝试提供示例 - 这将更容易理解

解决方案

特殊C ++样式,第7项:函数重载解析在模板专业化之前发生。不要混合重载的函数和模板函数的专业化,或者你是一个令人讨厌的惊喜,函数实际上被调用。

  template< class T> void f(T t){...} //(a)
template< class T> void f(T * t){...} //(b)
template<> void f< int *>(int * t){...} //(c)
...
int * pi; f(pi); //(b)被调用,而不是(c)!

项目7 顶部:


更糟糕的是,如果你忽略模板专业化中的类型,一个不同的函数模板可能会依赖于定义的顺序而被专门化,因此一个专门的函数可能会或可能不会



案例1:

 模板< class T& void f(T t){...} //(a)
template< class T> void f(T * t){...} //(b)
template<> void f(int * t){...} //(c) - specializes(b)
...
int * pi; f(pi); //(c)叫做

案例2:


$ b b

 模板< class T> void f(T t){...} //(a)
template<> void f(int * t){...} //(c) - specializes(a)
template< class T& void f(T * t){...} //(b)
...
int * pi; f(pi); //(b)被称为


What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...common mistakes/oversight/assumptions

I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice.

Let me formalize the question: What is the most important thing you've learned about templates?

Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly dry descriptions

Thanks

解决方案

From "Exceptional C++ style", Item 7: function overload resolution happens before templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called.

template<class T> void f(T t) { ... }   // (a)
template<class T> void f(T *t) { ... }  // (b)
template<> void f<int*>(int *t) { ... } // (c)
...
int *pi; f(pi); // (b) is called, not (c)!

On top of Item 7:

Worse yet, if you omit the type in template specialization, a different function template might get specialized depending on the order of definition and as a result a specialized function may or may not be called.

Case 1:

template<class T> void f(T t) { ... }  // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f(int *t) { ... }      // (c) - specializes (b)
...
int *pi; f(pi); // (c) is called

Case 2:

template<class T> void f(T t) { ... }  // (a)
template<> void f(int *t) { ... }      // (c) - specializes (a)
template<class T> void f(T *t) { ... } // (b)
...
int *pi; f(pi); // (b) is called

这篇关于关于C ++模板的最重要的事情...教训的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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