C ++:移动或分配

时间:2018-03-11 13:55:50

标签: c++

我有以下功能

template<typename OutClass,typename InClass>
OutClass & move_or_assign(InClass & IC){
    if(std::is_base_of<OutClass,InClass>::value)
        return std::move(IC);
    return IC;
}

这个函数编译,我的类有一个赋值运算符重载,实例化之间的赋值执行类型转换:

typeA<typeX> ax;

void function(typeA<typeX> & ax){
    typeA<typeY> ay = ax; // <-- works
}

理想情况下,我写道:

template<typename I>
void function(typeA<I> & ax){
   typeA<typeY> ay = move_or_assign(ax);
}
// such that ay is only "assigned" (which performs a deep copy)
// if I == typeX, but not if I == typeY

但是,当我调用它时,编译器会抱怨如下:

error: invalid initialization of non-const reference of type 
'A::typeY&' from an rvalue of 
type 'std::remove_reference<A::typeX&>::type {aka A::typeX}'

@ line:
if(std::is_base_of<OutClass,InClass>()) return std::move(IC);

不确定如何执行此操作,但似乎应该可行?

我会写出所有内容的情况的一个例子:

我有一个两个方向的数据结构。我需要以一个方向或另一个方向遍历数据结构。但是,我需要避免不必要的转换,因为它很大,所以我需要检查它的方向:

enum orientation {left,right}
struct Left{};
struct Right{};
template<class Dir>
struct DataStruct{};

template<typename data>
void function(data d,orientation dir){

    if(dir == left){
        if(std::is_base_of<data,DataStruct<Left>>::value){
            Data<Right> dr = d;
            loop_through(d,dr,some_func);
        }
        else loop_through(d,d,some_func);
    } else {
        // etc.
    }
}

我已经提出了这个light_copy_or_assign函数来替换内部的if语句:

// rather than: 
if(std::is_base_of<data,DataStruct<Left>>::value){
    Data<Right> dr = d;
    loop_through(d,dr,some_func);
}
else loop_through(d,d,some_func);

// I would write: 
Data<Right> dr = light_copy_or_assign(d);
loop_through(d,dr,some_func);

0 个答案:

没有答案