避免使用"const X&"和"X&"的两个版本的函数
Avoid two versions of function for `const X&` and `X&`
考虑以下代码:
template<typename X>
struct Store { X x; };
template<typename X>
Store<X> store(X x) { /* a lot of code */ return Store<X>{x}; }
void foo_cr(const int& a) {
auto s = store(a);
}
void foo_r(int& a) {
auto s = store(a);
}
有没有一种方法可以修改函数store
,使其在foo_cr
中返回Store<const int&>
,在foo_r
中返回Store<int&>
,而不为const X&
和X&
提供两个版本的store
?
现在我的代码是这样的:
template<typename X>
Store<const X&> store(const X& x) { /* a lot of code */ return Store<const X&>{x}; }
template<typename X>
Store<X&> store(X& x) { /* a lot of code */ return Store<X&>{x}; }
函数体完全相同,我希望避免重复的定义。
您可能正在寻找以下内容:
template<typename X>
Store<X&> store(X& xa)
{
auto x=xa;
/* a lot of code */
return Store<X&>{x};
}
它会将X
推导为Y
或const Y
,但它会将您限制为引用。此外,auto x=xa;
将确保在方法中获得类型Y
的副本。不确定这是否真的符合你的需求,但如果没有进一步的信息,很难说。
相关文章:
- CMake 库链接使用两个不同的编译器版本
- 为什么这两个版本的代码给出不同的输出
- g++ -O3 为 loop 创建了奇怪的指令 - 两个具有相同 asm 的版本
- 根据下面的作者,如果两个指针指向不同的数组,则比较的第一个版本将未定义
- 有两个不同版本的箭头运算符
- 应用程序中的两个不同版本的库
- 两个提升版本之间的冲突
- 在同一C++项目中链接两个不同版本的 protobuf 库
- 在发布版本中划分两个双精度的结果错误
- 如何在两个版本之间从perforce差异获取C/C 函数名称
- 我真的需要两个版本的==操作员超载吗?
- 如何在C 中输出两个字符串版本,一个具有逃生字符,另一个则不是
- 这两个版本的代码有什么区别
- 同一个应用程序中的同一库的两个版本
- 基于布尔标志有效地派生公共函数的两个版本
- 窗口如何处理加载两个不同版本的 DLL
- 特征 'sum()' 函数在两个版本的程序中给出不同的相同向量
- c++ 编译器优化是否可以针对布尔参数生成两个版本的函数
- 在安装了两个不同 Boost 版本的系统上编译C++代码
- 为什么这两个版本的快速排序在进行比较的次数上存在巨大差异