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

时间:2014-04-17 15:30:20

标签: c++ c++11

考虑以下代码:

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,使Store<const int&>中的foo_crStore<int&>中的foo_r返回store而不提供const X&的两个版本1}} X&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}; }


现在我的代码看起来像这样:

{{1}}

函数体完全相同,我想避免重复的定义。

1 个答案:

答案 0 :(得分:2)

您可能正在寻找以下内容:

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类型的副本。不确定这是否真的符合您的需求,但如果没有进一步的信息,很难说清楚。