避免使用"const X&"和"X&"的两个版本的函数

Avoid two versions of function for `const X&` and `X&`

本文关键字:版本 两个 函数 const      更新时间:2023-10-16

考虑以下代码:

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推导为Yconst Y,但它会将您限制为引用。此外,auto x=xa;将确保在方法中获得类型Y的副本。不确定这是否真的符合你的需求,但如果没有进一步的信息,很难说。