这是我的代码,作为背景:
template<typename... Dummy>
struct tuple;
template <typename T, typename... TList>
struct tuple<T,TList...>
:public tuple<TList...>
{
typedef T value_type;
tuple(){}
template<typename A,typename... AList>
tuple(const A& a,const AList&... args)
:tuple<TList...>(args...),element(a)
{
}
template<typename A,typename... AList>
tuple(A&& a,AList&&... args)
:tuple<TList...>(args...),element(a)
{
}
tuple(const tuple<T,TList...>& a)
:tuple<TList...>(a),element(a.element)
{
}
tuple(tuple<T,TList...>&& a)
:tuple<TList...>(a),element(a.element)
{
}
static const index_t size=1+tuple<TList...>::size;
static const index_t offset=sizeof(tuple<TList...>);
tuple_unit<T> element;
};
template<typename T>
struct tuple<T>
{
typedef T element_type;
tuple(){}
template<typename A>
tuple(const A& a)
:element(a)
{
}
template<typename A>
tuple(A&& a)
:element(a)
{
}
tuple(const tuple<T>& a)
:element(a.element)
{
}
tuple(tuple<T>&& a)
:element(a.element)
{
}
static const index_t size=1;
static const index_t offset=0;
tuple_unit<T> element;
};
由于在 C++11 中我们有移动语义,我尝试在我的项目中添加移动构造函数。但结果并不如我所料。
当我写
tuple<int,float,double> a(3,5,7); //Success. Use 3,5,7 to init each element in tuple.
tuple<int,float,double> b(a); //Call template function,not copy ctor,and it failed.
我读了这个,它让我认为b(a)
会调用template<typename A,typename... AList>
tuple(A&& a,AList&&... args)
,并且A& &&
会被替换A&
,但我已经有一个构造函数tuple(const tuple<T>& a)
。为什么编译器会认为模板构造函数比复制构造函数好?
我应该怎么做才能解决问题?