【发布时间】:2021-05-14 09:57:52
【问题描述】:
我考虑以下 2 个做同样事情的 sn-ps。在第一种情况下,我没有使用通用引用,因此我必须编写函数set 两次。在第二种情况下,使用通用引用我可以编写一次函数,但是该类的用户必须明确指定传递给函数set 的类型。有没有什么技巧可以兼得?
#include <iostream>
struct A {};
template<typename T>
struct B {
void set(const A& a) {
a_=a;
}
void set(A&& a) {
a_=std::forward<A>(a);
}
A a_;
};
int main() {
B<A> b;
A a;
b.set({});
b.set(a);
return 0;
}
和
#include <iostream>
struct A {};
template<typename T>
struct B {
template<typename U>
void set(U&& a) {
a_=std::forward<U>(a);
}
A a_;
};
int main() {
B<A> b;
A a;
b.set(A{}); // here I can't do b.set({}) because the template parameter U would be undefined
b.set(a);
return 0;
}
【问题讨论】:
标签: c++ perfect-forwarding type-deduction forwarding-reference