C ++:别名或初始化值

时间:2018-03-10 21:55:20

标签: c++ templates

假设我有一个模板类型A,其中包含两个实例A<X>A<Y>

假设我有一个模板函数,断言模板类型的类型为AA<X>A<Y>)。

此外,假设我可以使用赋值运算符在两种类型之间进行交换:

// given A<X> a, 
A<Y> ay = a; // <-- assignment converts the item

有没有办法可以执行以下操作(用伪代码编写):

// given A<Y> a, template type name Atype

A<Y> ay = std::is_base_of<A<Y>,Atype>::value ? alias(a) : a;

其中alias(a)创建某种别名 - 比如引用或指针,并且不需要复制或以其他方式运行整个赋值操作。

struct left{};
struct right{};

template<typename dir>
struct A{};

template<typename Atype>
function(Atype a){
    // assert Atype is either of 
    // A<left> or A<right>

    if(std::is_base_of<A<left>,Atype>::value)
        do_this(a);
    else{
        A<left> al = a; // <-- 3rd party library, O(sizeof(a)) operation, so necessary to check
        do_this(al);
    }
}

我要做的就是删除if语句,因为它在我的代码中是一个高度重复(即丑陋)的结构。想用一个函数替换它,但我觉得很难。

1 个答案:

答案 0 :(得分:0)

目前,我正在执行以下操作:

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