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 ...
随机推荐
- 锁 和 CopyOnWrite的实现
1.普通锁 只有lock功能, Java实现:ReentrantLock lock = new ReentrantLock(); lock和unlock: lock.lock(); lock.unlo ...
- css,html性能优化
css性能优化 CSS是负责布局和渲染的重要角色,漂亮的页面当然能够吸引用户.本文是自己在开发过程中总结的关于CSS与性能的关系,可能有不对之处,希望能够指出. ? 1.所有的样式尽量放在css文件中 ...
- Div.2 C. Dasha and Password
C. Dasha and Password time limit per test 2 seconds memory limit per test 256 megabytes input standa ...
- 制作jar文件
一.制作可运行jar文件 使用java的swing.awt制作了一个简单的界面交互模块.程序打成jar包后,能双击运行,制作过程: 1.eclipse →properties →Export,选择ja ...
- ArcGIS Pro 简明教程(2)基础操作和简单制图
ArcGIS Pro 简明教程(2)基础操作和简单制图 By 李远祥 本章主要介绍ArcGIS Pro如何加载数据并进行简单的地图制作,以基本的操作为主. 上一章节介绍过,ArcGIS Pro是可以直 ...
- C语言 一维数组叠加为二维数组样例
这里参看memcpy的用法,将一个一维整型数组不停的叠加为二维数组 使用宏定义来控制二维数组的行列 代码如下: #include <stdio.h> #include <stdlib ...
- Win8下,以管理员身份启动VS项目
之前一直是先以管理员身份启动VS,然后再打开项目的,比较麻烦,找了好久,总算有一个处理方案了 在Windows7下 通常使用修改属性的方式:在任意快捷方式上右击,选择属性,选择高级,选择以管理员身份启 ...
- C/C++中慎用宏(#define)
宏的定义在程序中是非常有用的,但是使用不当,就会给自身造成很大的困扰.通常这种困扰为:宏使用在计算方面. 本例子主要是在宏的计算方面,很多时候,大家都知道定义一个计算的宏,对于编译和编程是多么的有用. ...
- C++虚表(V-Table)解析
C++中的虚函数的作用主要是实现了多态,本人通过代码验证的方式了解虚表的结构及在多种继承方式下通过虚表访问子类函数.验证结果如下: 1)无虚函数覆盖的一般继承:可以通过子类的虚表访问父类的函数 2)虚 ...
- 前端开发面试题总结之——HTML
______________________________________________________________________________________________ 相关知识点 ...