C++:别名或初始化值

C++: alias or initialize a value

本文关键字:初始化 别名 C++      更新时间:2023-10-16

假设我有一个模板类型,A,有两个实例化A<X>A<Y>

假设我有一个模板函数,它断言模板类型为 A 类型(A<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 语句,因为它在我的代码中是一个高度重复(即丑陋(的结构。想用一个函数代替它,但我发现它非常困难。

现在,我正在执行以下内容:

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);
}