Effective Modern C++ Item 27:重载universal references
假设有一个接收universal references的模板函数foo,定义如下:
template<typename T>
void foo(T&& t)
{
cout << "foo(T&& t)" << endl;
}
如果想对某些类型做特殊处理,写一个重载版本的foo,比如想对float类型做特殊处理,就写一个接收float类型的foo:
void foo(float n)
{
cout << "foo(float n)" << endl;
}
这样,如果我们写下 foo(1.0) 时,理论上应该输出"foo(float n)",而实际上输出结果为"foo(T&& t)"。为什么呢?因为“Functions taking universal reference are the greediest functions in C++”,也就是说universal reference的函数能准确匹配几乎所有的类型。当我们调用foo(1.0)时,1.0被推导为double类型,如果调用foo(float n),就需要做narrow conversion,所以编译器会认为foo(T&& t)为更准确的匹配,除非我们写下foo(1.f)时,才会调用foo(float)。只有在类型完全准确匹配时,才会调用重载版本,否则编译器会始终认为universal reference版本为准确匹配。
这个问题在类继承中会更为隐晦,假设有一个名为Base的class,Base有一个接收universal reference的模板构造函数,定义如下:
class Base
{
public:
template<typename T>
explicit Base(T&& t)
{
cout << "Base(T&& t)" << endl;
} Base(const Base& b)
{
cout << "Base(const Base& b)" << endl;
} Base(Base&& b)
{
cout << "Base(Base&& b)" << endl;
} Base() = default;
};
然后Derived继承Base:
class Derived : public Base
{
public:
Derived() = default; Derived(const Derived& d)
:Base(d)
{
} Derived(Derived&& d)
:Base(std::move(d))
{
}
};
这时候,如果我们写:
Derived a;
Derived b(a);
Derived c(std::move(a));
那么输出结果始终为“Base(T&& t)”,也就是在Derived的拷贝构造和移动构造中,Base的函数调用都是Base(T&& t)。因为传给Base的类型为Derived,所以编译器始终认为universal reference为准确匹配。
由于universal reference的匹配过于"strong",一般都要避免重载,否则很容易出现匹配结果和预期不一致的情况。
如果无法避免重载呢?有两种方法:
1.使用type tags
考虑之前的foo函数,我们不重载foo函数,而是编写两个重载的fooImpl,fooImpl一个接受universal reference,一个接受float,两个函数用type tag参数来区分:
template<typename T>
void fooImpl(T&& t, std::false_type)
{
cout << "fooImpl(T&& t)" << endl;
} void fooImpl(float t, std::true_type)
{
cout << "fooImpl(float t)" << endl;
}
参数的type tag表示是否为浮点类型,那么foo就可以这么调用:
template<typename T>
void foo(T&& t)
{
fooImpl(std::forward<T>(t), std::is_floating_point<std::remove_reference_t<T>>());
}
这样有了type tag,只要参数是浮点类型,都会调用float版本的fooImpl。
2. 使用enable_if约束universal reference
如果某些情况我们不想使用universal reference版本,那么可以使用enable_if把它在重载决议的候选函数中屏蔽掉(SFINAE机制)。
对于foo函数,改写为:
template<typename T, typename = std::enable_if_t<
!std::is_floating_point<
std::remove_reference_t<T>
>::value>
>
void foo(T&& t)
{
cout << "foo(T&& t)" << endl;
} void foo(float t)
{
cout << "foo(float t)" << endl;
}
这样,如果参数为浮点类型,foo(T&& t)会被屏蔽掉,就会调用float版本的foo,这就和预期结果一致。
对于之前的Base class,思路也是一样的。用enable_if改写之前的代码:
class Base
{
public:
template<typename T, typename = std::enable_if_t<
!std::is_base_of <Base, std::decay_t<T>>::value
>>
explicit Base(T&& t)
{
cout << "Base(T&& t)" << endl;
} Base(const Base& b)
{
cout << "Base(const Base& b)" << endl;
} Base(Base&& b)
{
cout << "Base(Base&& b)" << endl;
} Base() = default;
};
这样,Derived的拷贝构造和移动构造就能正确调用到Base的函数(std::decay去掉references和cv-qualifiers)。
结论:
1. 尽量避免重载universal references模板函数。
2. 如果无法避免,使用type tags或者enable_if来编写重载函数。
Effective Modern C++ Item 27:重载universal references的更多相关文章
- [Effective Modern C++] Item 1. Understand template type deduction - 了解模板类型推断
条款一 了解模板类型推断 基本情况 首先定义函数模板和函数调用的形式如下,在编译期间,编译器推断T和ParamType的类型,两者基本不相同,因为ParamType常常包含const.引用等修饰符 t ...
- [Effective Modern C++] Item 7. Distinguish between () and {} when creating objects - 辨别使用()与{}创建对象的差别
条款7 辨别使用()与{}创建对象的差别 基础知识 目前已知有如下的初始化方式: ); ; }; }; // the same as above 在以“=”初始化的过程中没有调用赋值运算,如下例所示: ...
- [Effective Modern C++] Item 6. Use the explicitly typed initializer idiom when auto deduces undesired types - 当推断意外类型时使用显式的类型初始化语句
条款6 当推断意外类型时使用显式的类型初始化语句 基础知识 当使用std::vector<bool>的时候,类型推断会出现问题: std::vector<bool> featu ...
- [Effective Modern C++] Item 5. Prefer auto to explicit type declarations - 相对显式类型声明,更倾向使用auto
条款5 相对显式类型声明,更倾向使用auto 基础知识 auto能大大方便变量的定义,可以表示仅由编译器知道的类型. template<typename It> void dwim(It ...
- [Effective Modern C++] Item 4. Know how to view deduced types - 知道如何看待推断出的类型
条款四 知道如何看待推断出的类型 基础知识 有三种方式可以知道类型推断的结果: IDE编辑器 编译器诊断 运行时输出 使用typeid()以及std::type_info::name可以获取变量的类型 ...
- [Effective Modern C++] Item 3. Understand decltype - 了解decltype
条款三 了解decltype 基础知识 提供一个变量或者表达式,decltype会返回其类型,但是返回的内容会使人感到奇怪. 以下是一些简单的推断类型: ; // decltype(i) -> ...
- [Effective Modern C++] Item 2. Understand auto type deduction - 了解auto类型推断
条款二 了解auto类型推断 基础知识 除了一处例外,auto的类型推断与template一样.存在一个直接的从template类型推断到auto类型推断的映射 三类情况下的推断如下所示: // ca ...
- Effective Modern C++ Item 37:确保std::thread在销毁时是unjoinable的
下面这段代码,如果调用func,按照C++的标准,程序会被终止(std::terminate) void func() { std::thread t([] { std::chrono::micros ...
- Effective Modern C++ 42 Specific Ways to Improve Your Use of C++11 and C++14
Item 1: Understand template type deduction. Item 2: Understand auto type deduction. Item 3: Understa ...
随机推荐
- removeEventListener('2016');
2016----最后一天工作日要快结束了,趁剩下的一点时间写篇博客玩玩,想到啥就写啥.总结下来就一句---累并快乐着... 先祝大家新年快乐!万事如意发大财. 一年跳了三家公司,上半年在家小公司干着整 ...
- webservice_模拟报文测试
一.WebService测试小工具STORM 二.利用MyEclipse的WebService视图调用webservice Ø 除了客户端生成代码编写程序调用之外.还可以用MyEclipse提供 ...
- Java中正则表达式去除html标签
Java中正则表达式去除html的标签,主要目的更精确的显示内容,比如前一段时间在做类似于博客中发布文章功能,当编辑器中输入内容后会将样式标签也传入后台并且保存数据库,但是在显示摘要的时候,比如显示正 ...
- 解决 Eclipse build workspace validation javascript 慢的问题
参考: http://blog.csdn.net/zhangzikui/article/details/24805935 http://www.cnblogs.com/wql025/p/4978351 ...
- tableView的总结
// // ViewController.m // TableViewController // // Created by 王妍 on 16/3/23. // Copyright © 2016年 c ...
- ajax提交File文件
<script type="text/javascript"> $(function() { $("input[name='image'] ...
- C++STL笔记
C++STL 1.vector 向量,长度可变的数组 头文件 #include<vector> 1.1vector的定义 vector<typename> name; 例如: ...
- Unity中的万能对象池
本文为博主原创文章,欢迎转载.请保留博主链接http://blog.csdn.net/andrewfan Unity编程标准导引-3.4 Unity中的万能对象池 本节通过一个简单的射击子弹的示例来介 ...
- H5常见的兼容问题及解决
最近这两天经常遇到一些麻烦的兼容问题,统一整理一下,比较简单也不是特别全面,希望大家多多交流. 几种IE6 bug的解决方法 1)png24位的图片在iE6浏览器上出现背景,解决方案是做成PNG8.也 ...
- PHP基础学习(函数一)
PHP(Hypertext Preprocessor):超文本预处理器,一种嵌入在HTML中并且运行在服务器端的脚本语言. var_dump--打印变量相关信息 说明: <?php var_d ...