考虑以下代码:
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_cr
和Store<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}}
函数体完全相同,我想避免重复的定义。
答案 0 :(得分:2)
您可能正在寻找以下内容:
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
类型的副本。不确定这是否真的符合您的需求,但如果没有进一步的信息,很难说清楚。