【发布时间】:2014-01-27 21:03:21
【问题描述】:
在尝试为 shared_ptr 编写一个包装器时,它会在支持继承类的同时隐藏用户的内存分配和释放,我偶然发现了非常奇怪的错误,表明编译器在重载期间查找错误的函数,或者我的知识关于混合重载和模板是错误的。所以我写了这个东西来测试:
#include <iostream>
void out(int i) {
std::cout << i << '\n';
}
template <class T>
struct Inst {
template <class TT>
Inst(const TT &) {out(1);}
Inst(const Inst &) {out(2);}
template <class TT>
Inst(TT &&) {out(3);}
Inst(Inst &&) {out(4);}
Inst() {out(-1);}
~Inst() {out(1000);}
};
class K {};
class KK : K {};
int main() {
out(3000);
K k; KK kk; Inst<K> i;
Inst<K> I1{k};
Inst<K> I2{kk};
Inst<K> I3{i};
Inst<K> I4{K()};
Inst<K> I5{KK()};
Inst<K> I6{Inst<K>()};
out(2000);
}
我的合理预期是I1 和I2 写作1、I3 写作2、I4 和I5 写作3 和I6 写作@98765433以及至少两个其他对象在不同点写-1。但是,当使用 gcc 4.8.2 使用 -std=c++11 编译时,我的机器跳过了一个对象,并为每个其他调用的非自动构造函数编写了 3。我做错了什么?
【问题讨论】:
-
我认为您对
&&和“通用引用”有些困惑。见:isocpp.org/blog/2012/11/… -
你可以找到this easier to read。
标签: c++ templates template-specialization specialization