C++:别名或初始化值
C++: alias or initialize a value
假设我有一个模板类型,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);
}
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- C++:别名或初始化值
- 如何初始化struct []或制作别名或将C 中的现有struct []指向
- 如何将所有别名、声明和初始化放在一起
- 将预定但非初始化的向量设置为另一个别名
- 为什么 std::shared_ptr 的别名构造函数不初始化 std::enabled_shared_from_this?